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 |
||
6 | class Model implements \IteratorAggregate |
||
7 | { |
||
8 | protected $client; |
||
9 | private $_data; |
||
10 | |||
11 | public function __construct(GoogleBooks $client, $data) |
||
16 | |||
17 | /** |
||
18 | * Set data for this model |
||
19 | */ |
||
20 | protected function setData(\stdClass $data) |
||
24 | |||
25 | /** |
||
26 | * Returns true if the model is created from a search result response |
||
27 | * (and thus do not contain all the data of the full record). |
||
28 | * |
||
29 | * @return bool |
||
30 | */ |
||
31 | public function isSearchResult() |
||
35 | |||
36 | /** |
||
37 | * Expand a search result response object to a full record. |
||
38 | */ |
||
39 | public function expandToFullRecord() |
||
43 | |||
44 | /** |
||
45 | * Special method that allows the object to be iterated over, for example |
||
46 | * with a foreach statement. |
||
47 | */ |
||
48 | public function getIterator() { |
||
51 | |||
52 | /** |
||
53 | * Get an item from an array using "dot" notation. |
||
54 | * |
||
55 | * @param string $key |
||
56 | * @param mixed $default |
||
57 | * @return mixed |
||
58 | */ |
||
59 | View Code Duplication | public function get($key, $default = null) |
|
70 | |||
71 | /** |
||
72 | * Check if an item or items exist in an array using "dot" notation. |
||
73 | * |
||
74 | * @param string $key |
||
75 | * @return mixed |
||
76 | */ |
||
77 | View Code Duplication | public function has($key) |
|
88 | |||
89 | /** |
||
90 | * Get a string representation of the object |
||
91 | * |
||
92 | * @return string |
||
93 | */ |
||
94 | public function __toString() |
||
98 | |||
99 | /** |
||
100 | * Provide object-like access to the data. |
||
101 | * |
||
102 | * @param string $key |
||
103 | * @return mixed |
||
104 | */ |
||
105 | public function __get($key) |
||
109 | } |
||
110 |
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.