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 ArraySet extends AbstractSet |
||
17 | { |
||
18 | /** |
||
19 | * The set elements |
||
20 | * |
||
21 | * @var array |
||
22 | */ |
||
23 | protected $elements = []; |
||
24 | |||
25 | /** |
||
26 | * Constructor |
||
27 | * |
||
28 | * @param array $elements |
||
29 | */ |
||
30 | 4 | public function __construct(array $elements = []) |
|
34 | |||
35 | /** |
||
36 | * Returns true if the collection contains element |
||
37 | * |
||
38 | * @param mixed $element |
||
39 | * @return bool |
||
40 | */ |
||
41 | 33 | public function contains($element): bool |
|
45 | |||
46 | /** |
||
47 | * Ensure the element exists in the collection |
||
48 | * |
||
49 | * Returns true if the collection can contain duplicates, |
||
50 | * and false if it cannot. |
||
51 | * |
||
52 | * @param mixed $element |
||
53 | * @return bool |
||
54 | */ |
||
55 | 33 | public function add($element): bool |
|
65 | |||
66 | /** |
||
67 | * Removes all elements from a collection |
||
68 | * |
||
69 | * @return void |
||
70 | */ |
||
71 | 1 | public function clear(): void |
|
75 | |||
76 | /** |
||
77 | * Removes object if it exists |
||
78 | * |
||
79 | * Returns true if the element was removed |
||
80 | * |
||
81 | * @param mixed $element |
||
82 | * @return bool |
||
83 | */ |
||
84 | 8 | View Code Duplication | public function remove($element): bool |
96 | |||
97 | /** |
||
98 | * Returns an array of all elements in the collection |
||
99 | * |
||
100 | * @return array |
||
101 | */ |
||
102 | 33 | public function toArray(): array |
|
106 | |||
107 | /** |
||
108 | * Retrieve an external iterator |
||
109 | * |
||
110 | * @return ArrayIterator |
||
111 | */ |
||
112 | 8 | public function getIterator(): ArrayIterator |
|
116 | } |
||
117 |
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.