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 LanguageRepository |
||
15 | { |
||
16 | /** |
||
17 | * Database table name that this repository maintains. |
||
18 | * |
||
19 | * @var string |
||
20 | */ |
||
21 | const TABLE = 'languages'; |
||
22 | |||
23 | /** |
||
24 | * @var Connection |
||
25 | */ |
||
26 | private $connection; |
||
27 | |||
28 | /** |
||
29 | * LanguageRepository constructor. |
||
30 | * |
||
31 | * @param Connection $connection |
||
32 | */ |
||
33 | public function __construct(Connection $connection) |
||
37 | |||
38 | /** |
||
39 | * Fetches all languages. |
||
40 | * |
||
41 | * @return LanguageEntity[] |
||
42 | */ |
||
43 | View Code Duplication | public function fetchAll() |
|
58 | |||
59 | /** |
||
60 | * Fetches all translated languages. |
||
61 | * |
||
62 | * @return LanguageEntity[] |
||
63 | */ |
||
64 | View Code Duplication | public function fetchAllTranslated() |
|
80 | |||
81 | /** |
||
82 | * Creates a language in the database. |
||
83 | * |
||
84 | * @param LanguageEntity $entity |
||
85 | * |
||
86 | * @return LanguageEntity |
||
87 | */ |
||
88 | View Code Duplication | public function create(LanguageEntity $entity) |
|
89 | { |
||
90 | if (!$entity->isNew()) { |
||
91 | throw new InvalidArgumentException('The entity does already exist.'); |
||
92 | } |
||
93 | |||
94 | $this->connection->insert( |
||
95 | self::TABLE, |
||
96 | $entity->toDatabaseArray() |
||
97 | ); |
||
98 | |||
99 | $entity->short = $this->connection->lastInsertId(); |
||
100 | |||
101 | return $entity; |
||
102 | } |
||
103 | |||
104 | /** |
||
105 | * Update a language in the database. |
||
106 | * |
||
107 | * @param LanguageEntity $entity |
||
108 | * |
||
109 | * @return LanguageEntity |
||
110 | */ |
||
111 | View Code Duplication | public function update(LanguageEntity $entity) |
|
127 | |||
128 | /** |
||
129 | * Removes a language from the database. |
||
130 | * |
||
131 | * @param LanguageEntity $entity |
||
132 | * |
||
133 | * @return LanguageEntity |
||
134 | */ |
||
135 | View Code Duplication | public function remove(LanguageEntity $entity) |
|
151 | |||
152 | /** |
||
153 | * Converts database array to entity array. |
||
154 | * |
||
155 | * @param array $result |
||
156 | * |
||
157 | * @return LanguageEntity[] |
||
158 | */ |
||
159 | private function getEntityArrayFromDatabaseArray(array $result) |
||
169 | } |
||
170 |
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.