Complex classes like GuardTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use GuardTrait, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 8 | trait GuardTrait |
||
| 9 | { |
||
| 10 | abstract function isEmpty(); |
||
| 11 | |||
| 12 | abstract function count(); |
||
| 13 | |||
| 14 | protected function emptyGuard($method) |
||
| 15 | { |
||
| 16 | if ($this->isEmpty()) { |
||
| 17 | throw new EmptyException( |
||
| 18 | "{$method} cannot be called when the structure is empty" |
||
| 19 | ); |
||
| 20 | } |
||
| 21 | } |
||
| 22 | |||
| 23 | 5 | protected function validateKeyBounds($k) |
|
| 29 | |||
| 30 | /** |
||
| 31 | * @param int $element |
||
| 32 | * @return mixed |
||
| 33 | */ |
||
| 34 | 5 | protected function isBoundedKey($element) |
|
| 38 | |||
| 39 | 22 | protected function validateKeyType($element) |
|
| 45 | } |
||
| 46 |
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.