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:
1 | <?php |
||
16 | class Container |
||
17 | { |
||
18 | /** |
||
19 | * Contains the values (either input or output). |
||
20 | * |
||
21 | * @var array |
||
22 | */ |
||
23 | protected $values = []; |
||
24 | |||
25 | /** |
||
26 | * Construct the Value\Container. |
||
27 | * |
||
28 | * @param array $values |
||
29 | */ |
||
30 | 159 | public function __construct(array $values = []) |
|
34 | |||
35 | /** |
||
36 | * Determines whether or not the container has a value for key $key. |
||
37 | * |
||
38 | * @param string $key |
||
39 | * @return bool |
||
40 | */ |
||
41 | 155 | public function has($key) |
|
45 | |||
46 | /** |
||
47 | * Returns the value for the key $key, or null if the value doesn't exist. |
||
48 | * |
||
49 | * @param string $key |
||
50 | * @return mixed |
||
51 | */ |
||
52 | 144 | public function get($key) |
|
56 | |||
57 | /** |
||
58 | * Removes a value from the container |
||
59 | * |
||
60 | * @param string $key |
||
61 | */ |
||
62 | 6 | public function remove($key) |
|
73 | |||
74 | /** |
||
75 | * Set the value of $key to $value. |
||
76 | * |
||
77 | * @param string $key |
||
78 | * @param mixed $value |
||
79 | * @return $this |
||
80 | */ |
||
81 | 150 | public function set($key, $value) |
|
89 | |||
90 | /** |
||
91 | * Returns a plain array representation of the Value\Container object. |
||
92 | * |
||
93 | * @return array |
||
94 | */ |
||
95 | 159 | public function getArrayCopy() |
|
99 | |||
100 | /** |
||
101 | * Traverses the key using dot notation. Based on the second parameter, it will return the value or if it was set. |
||
102 | * |
||
103 | * @param string $key |
||
104 | * @param bool $returnValue |
||
105 | * @return mixed |
||
106 | */ |
||
107 | 155 | protected function traverse($key, $returnValue = true) |
|
118 | |||
119 | /** |
||
120 | * Uses dot-notation to set a value. |
||
121 | * |
||
122 | * @param string $key |
||
123 | * @param mixed $value |
||
124 | * @return $this |
||
125 | */ |
||
126 | 4 | protected function setTraverse($key, $value) |
|
138 | } |
||
139 |
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.