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 Reductions 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 Reductions, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
10 | class Reductions |
||
11 | { |
||
12 | /** |
||
13 | * Returns a closure that adds two numbers together |
||
14 | * |
||
15 | * @return \Closure |
||
16 | */ |
||
17 | 30 | View Code Duplication | public static function add() |
29 | |||
30 | /** |
||
31 | * Returns a closure that subtracts one number from another |
||
32 | * |
||
33 | * @return \Closure |
||
34 | */ |
||
35 | 20 | View Code Duplication | public static function sub() |
47 | |||
48 | /** |
||
49 | * Returns a closure that multiplies two numbers |
||
50 | * |
||
51 | * @return \Closure |
||
52 | */ |
||
53 | 18 | View Code Duplication | public static function mul() |
65 | |||
66 | /** |
||
67 | * Returns a closure that returns the smallest of two numbers |
||
68 | * |
||
69 | * @return \Closure |
||
70 | */ |
||
71 | 19 | View Code Duplication | public static function min() |
83 | |||
84 | /** |
||
85 | * Returns a closure that returns the largest of two numbers |
||
86 | * |
||
87 | * @return \Closure |
||
88 | */ |
||
89 | 19 | View Code Duplication | public static function max() |
101 | |||
102 | /** |
||
103 | * Returns a closure that concatenates two strings using $glue |
||
104 | * |
||
105 | * @param string $glue |
||
106 | * @return \Closure |
||
107 | */ |
||
108 | 22 | public static function join($glue = '') |
|
123 | |||
124 | /** |
||
125 | * @deprecated please use the reduction functions directly, will be removed in version 3.0 |
||
126 | * @param string $name |
||
127 | * @param null $default |
||
128 | * @return \Closure|null |
||
129 | */ |
||
130 | public static function getReduction($name, $default = null) |
||
149 | } |
||
150 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.