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 |
||
10 | abstract class FileEntity extends AbstractEntity implements EntityInterface |
||
11 | { |
||
12 | protected $extension; |
||
13 | |||
14 | /** |
||
15 | * Returns the base path. |
||
16 | * |
||
17 | * @return string |
||
18 | */ |
||
19 | abstract protected function getBasePath(); |
||
20 | |||
21 | protected function getIterator() |
||
25 | |||
26 | /** |
||
27 | * {@inheritdoc} |
||
28 | */ |
||
29 | public function search(SearchQuery $search = null) |
||
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | */ |
||
58 | View Code Duplication | public function create(array $data) |
|
67 | |||
68 | /** |
||
69 | * {@inheritdoc} |
||
70 | */ |
||
71 | public function read($id) |
||
77 | |||
78 | /** |
||
79 | * {@inheritdoc} |
||
80 | */ |
||
81 | View Code Duplication | public function update($id, array $data) |
|
90 | |||
91 | /** |
||
92 | * {@inheritdoc} |
||
93 | */ |
||
94 | public function delete($id) |
||
100 | |||
101 | /** |
||
102 | * Calculate the id of a new row. |
||
103 | * |
||
104 | * @param array $data |
||
105 | * |
||
106 | * @return string |
||
107 | */ |
||
108 | protected function getId(array $data) |
||
112 | |||
113 | /** |
||
114 | * Returns the path of a file. |
||
115 | * |
||
116 | * @return string |
||
117 | */ |
||
118 | protected function getFilePath($filename) |
||
122 | |||
123 | /** |
||
124 | * Transform the data to a string. |
||
125 | * |
||
126 | * @param array $data |
||
127 | * |
||
128 | * @return string |
||
129 | */ |
||
130 | abstract protected function stringify(array $data); |
||
131 | |||
132 | /** |
||
133 | * Transform the string to an array. |
||
134 | * |
||
135 | * @param string $source |
||
136 | * |
||
137 | * @return array |
||
138 | */ |
||
139 | abstract protected function parse($source); |
||
140 | } |
||
141 |
If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe: