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 |
||
13 | class Identity extends DataMapper |
||
14 | { |
||
15 | |||
16 | /** |
||
17 | * @param Entity\Identity $entity |
||
18 | */ |
||
19 | 1 | public function store(Entity\Identity $entity) |
|
20 | { |
||
21 | 1 | $sql = "UPDATE {$this->table} |
|
22 | SET used_on = :used, |
||
23 | status = :status |
||
24 | WHERE identity_id = :id"; |
||
25 | |||
26 | 1 | $statement = $this->connection->prepare($sql); |
|
27 | |||
28 | 1 | $statement->bindValue(':id', $entity->getId()); |
|
29 | 1 | $statement->bindValue(':used', $entity->getLastUsed()); |
|
30 | 1 | $statement->bindValue(':status', $entity->getStatus()); |
|
31 | |||
32 | 1 | $statement->execute(); |
|
33 | 1 | } |
|
34 | |||
35 | |||
36 | /** |
||
37 | * @param Entity\Identity $entity |
||
38 | */ |
||
39 | public function remove(Entity\Identity $entity) |
||
40 | { |
||
41 | $sql = "DELETE FROM {$this->table} WHERE identity_id = :id"; |
||
42 | $statement = $this->connection->prepare($sql); |
||
43 | |||
44 | $statement->bindValue(':id', $entity->getId()); |
||
45 | $statement->execute(); |
||
46 | } |
||
47 | |||
48 | |||
49 | /** |
||
50 | * @param Entity\Identity $entity |
||
51 | */ |
||
52 | 1 | public function fetch(Entity\Identity $entity) |
|
53 | |||
54 | { |
||
55 | 1 | if ($entity->getId()) { |
|
56 | 1 | $this->fetchById($entity); |
|
57 | 1 | return; |
|
58 | } |
||
59 | |||
60 | $this->fetchByToken($entity); |
||
61 | } |
||
62 | |||
63 | |||
64 | 1 | private function fetchById(Entity\Identity $entity) |
|
87 | |||
88 | |||
89 | View Code Duplication | private function fetchByToken(Entity\Identity $entity) |
|
|
|||
90 | { |
||
120 | } |
||
121 |
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.