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 |
||
30 | class IndexOptions implements \JsonSerializable { |
||
31 | |||
32 | /** |
||
33 | * @var array |
||
34 | */ |
||
35 | private $options = []; |
||
36 | |||
37 | |||
38 | public function __construct($options = []) { |
||
41 | |||
42 | /** |
||
43 | * @return array |
||
44 | */ |
||
45 | public function getOptions() { |
||
48 | |||
49 | /** |
||
50 | * @param array $options |
||
51 | */ |
||
52 | public function setOptions($options) { |
||
55 | |||
56 | /** |
||
57 | * @param string $k |
||
58 | * @param string $v |
||
59 | */ |
||
60 | public function addOption($k, $v) { |
||
63 | |||
64 | /** |
||
65 | * @param string $k |
||
66 | * @param array $array |
||
67 | */ |
||
68 | public function addOptionArray($k, $array) { |
||
71 | |||
72 | /** |
||
73 | * @param string $k |
||
74 | * @param bool $bool |
||
75 | */ |
||
76 | public function addOptionBool($k, $bool) { |
||
79 | |||
80 | |||
81 | /** |
||
82 | * @param string $k |
||
83 | * @param string $default |
||
84 | * |
||
85 | * @return string |
||
86 | */ |
||
87 | public function getOption($k, $default = '') { |
||
94 | |||
95 | |||
96 | /** |
||
97 | * @param string $option |
||
98 | * @param array $default |
||
99 | * |
||
100 | * @return array |
||
101 | */ |
||
102 | View Code Duplication | public function getOptionArray($option, $default = []) { |
|
112 | |||
113 | |||
114 | /** |
||
115 | * @param string $option |
||
116 | * @param bool $default |
||
117 | * |
||
118 | * @return bool |
||
119 | */ |
||
120 | View Code Duplication | public function getOptionBool($option, $default) { |
|
130 | |||
131 | |||
132 | /** |
||
133 | * Specify data which should be serialized to JSON |
||
134 | * |
||
135 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
136 | * @return mixed data which can be serialized by <b>json_encode</b>, |
||
137 | * which is a value of any type other than a resource. |
||
138 | * @since 5.4.0 |
||
139 | */ |
||
140 | public function jsonSerialize() { |
||
143 | } |
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.