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 |
||
23 | class HasAndBelongsToMany extends HasMany |
||
24 | { |
||
25 | |||
26 | /** |
||
27 | * @readwrite |
||
28 | * @var string |
||
29 | */ |
||
30 | protected $relatedForeignKey; |
||
31 | |||
32 | /** |
||
33 | * @readwrite |
||
34 | * @var string |
||
35 | */ |
||
36 | protected $relationTable; |
||
37 | |||
38 | /** |
||
39 | * Gets the related foreign key |
||
40 | * |
||
41 | * @return string |
||
42 | */ |
||
43 | 4 | public function getRelatedForeignKey() |
|
51 | |||
52 | /** |
||
53 | * Gets the related table |
||
54 | * |
||
55 | * @return string |
||
56 | */ |
||
57 | 4 | public function getRelationTable() |
|
71 | |||
72 | /** |
||
73 | * Loads the entity or entity collection for this relation |
||
74 | * |
||
75 | * @param EntityInterface $entity |
||
76 | * |
||
77 | * @return EntityCollectionInterface|EntityInterface[] |
||
78 | */ |
||
79 | 2 | View Code Duplication | public function load(EntityInterface $entity) |
100 | |||
101 | /** |
||
102 | * Saves the relation row upon entity add |
||
103 | * |
||
104 | * @param EntityAdded $event |
||
105 | */ |
||
106 | public function add(EntityAdded $event) |
||
110 | |||
111 | /** |
||
112 | * Gets the relation conditions |
||
113 | * |
||
114 | * @param EntityInterface $entity |
||
115 | * @return array |
||
116 | */ |
||
117 | 2 | protected function getConditions(EntityInterface $entity) |
|
127 | |||
128 | /** |
||
129 | * Adds the join table to the query |
||
130 | * |
||
131 | * @param Select $query |
||
132 | * @return self |
||
133 | */ |
||
134 | 2 | protected function addJoinTable(Select $query) |
|
148 | |||
149 | } |
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.