Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Accessor 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 Accessor, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
11 | class Accessor |
||
12 | { |
||
13 | /** |
||
14 | * @var mixed |
||
15 | */ |
||
16 | protected $data; |
||
17 | |||
18 | /** |
||
19 | * @var mixed |
||
20 | */ |
||
21 | protected $current; |
||
22 | |||
23 | /** |
||
24 | * @param mixed $data |
||
25 | */ |
||
26 | 3 | public function __construct($data) |
|
36 | |||
37 | /** |
||
38 | * @return mixed |
||
39 | */ |
||
40 | 2 | public function getData() |
|
44 | |||
45 | /** |
||
46 | * @return mixed |
||
47 | */ |
||
48 | 1 | public function getCurrent() |
|
52 | |||
53 | /** |
||
54 | * Navigates to `$key`. |
||
55 | * |
||
56 | * @param string|int $key |
||
57 | * |
||
58 | * @return bool `true` if it is possible to navigate to `$key`, `false` if not |
||
59 | */ |
||
60 | 21 | public function to($key) |
|
90 | |||
91 | /** |
||
92 | * @param string|int $key |
||
93 | * @param mixed $value |
||
94 | * |
||
95 | * @return bool |
||
96 | */ |
||
97 | 14 | public function set($key, $value) |
|
117 | |||
118 | /** |
||
119 | * @param string|int $key |
||
120 | * |
||
121 | * @return bool |
||
122 | */ |
||
123 | 23 | public function has($key) |
|
139 | |||
140 | /** |
||
141 | * @param string|int $key |
||
142 | * |
||
143 | * @return bool |
||
144 | */ |
||
145 | 7 | public function remove($key) |
|
166 | |||
167 | /** |
||
168 | * @param mixed $data |
||
169 | * @param string|int $key |
||
170 | * |
||
171 | * @return bool |
||
172 | */ |
||
173 | 18 | protected function isObjectWithMethod($data, $key) |
|
177 | } |
||
178 |
This check examines a number of code elements and verifies that they conform to the given naming conventions.
You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.