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 |
||
14 | class LogList implements JsonSerializable { |
||
15 | |||
16 | /** |
||
17 | * @var Log[] |
||
18 | */ |
||
19 | private $logs; |
||
20 | |||
21 | /** |
||
22 | * @param Log[] $logs |
||
23 | 1 | */ |
|
24 | 1 | public function __construct( $logs = [] ) { |
|
28 | |||
29 | /** |
||
30 | * @param Log[]|LogList $logs |
||
31 | * |
||
32 | * @throws InvalidArgumentException |
||
33 | 1 | */ |
|
34 | 1 | View Code Duplication | public function addLogs( $logs ) { |
45 | |||
46 | /** |
||
47 | * @param Log $log |
||
48 | 1 | */ |
|
49 | 1 | public function addLog( Log $log ) { |
|
52 | |||
53 | /** |
||
54 | * @param int $id |
||
55 | * |
||
56 | * @return bool |
||
57 | */ |
||
58 | public function hasLogWithId( $id ) { |
||
61 | |||
62 | /** |
||
63 | * @param Log $log |
||
64 | * |
||
65 | * @return bool |
||
66 | */ |
||
67 | public function hasLog( Log $log ) { |
||
70 | |||
71 | /** |
||
72 | * @return Log|null Log or null if there is no log |
||
73 | */ |
||
74 | public function getLatest() { |
||
80 | |||
81 | /** |
||
82 | * @since 0.6 |
||
83 | * @return Log|null Log or null if there is no log |
||
84 | */ |
||
85 | public function getOldest() { |
||
91 | |||
92 | /** |
||
93 | * @since 0.6 |
||
94 | * @return bool |
||
95 | */ |
||
96 | public function isEmpty() { |
||
99 | |||
100 | /** |
||
101 | * @param int $id |
||
102 | * |
||
103 | * @throws RuntimeException |
||
104 | * @return Log |
||
105 | */ |
||
106 | public function get( $id ) { |
||
112 | |||
113 | /** |
||
114 | * @return Log[] |
||
115 | 1 | */ |
|
116 | 1 | public function toArray() { |
|
119 | |||
120 | /** |
||
121 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
122 | 1 | */ |
|
123 | 1 | public function jsonSerialize() { |
|
126 | |||
127 | /** |
||
128 | * @param array $json |
||
129 | * |
||
130 | * @return self |
||
131 | 1 | */ |
|
132 | 1 | public static function jsonDeserialize( $json ) { |
|
139 | } |
||
140 |
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.