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 |
||
27 | class CartComponent extends Component |
||
28 | { |
||
29 | |||
30 | /** |
||
31 | * @var array |
||
32 | */ |
||
33 | protected $_defaultConfig = [ |
||
34 | 'storage' => \Cart\Storage\SessionStorage::class |
||
35 | ]; |
||
36 | |||
37 | /** |
||
38 | * @var array |
||
39 | */ |
||
40 | protected $_objects = []; |
||
41 | |||
42 | /** |
||
43 | * @var \Cart\Storage\StorageInterface |
||
44 | */ |
||
45 | protected $_storage; |
||
46 | |||
47 | /** |
||
48 | * @param array $config |
||
49 | */ |
||
50 | public function initialize(array $config) |
||
56 | |||
57 | /** |
||
58 | * @param \Cart\Entity\EntityPriceAwareInterface $entity |
||
59 | * @param int $quantity |
||
60 | * @return bool |
||
61 | * @throws \Exception |
||
62 | */ |
||
63 | public function add(\Cart\Entity\EntityPriceAwareInterface $entity, $quantity = 1) |
||
76 | |||
77 | /** |
||
78 | * @param \Cart\Entity\EntityPriceAwareInterface $entity |
||
79 | * @param int $quantity |
||
80 | * @return bool |
||
81 | * @throws \Exception |
||
82 | */ |
||
83 | public function edit(\Cart\Entity\EntityPriceAwareInterface $entity, $quantity = 1) |
||
97 | |||
98 | /** |
||
99 | * @param \Cart\Entity\EntityPriceAwareInterface $entity |
||
100 | * @return bool |
||
101 | * @throws \Exception |
||
102 | */ |
||
103 | public function delete(\Cart\Entity\EntityPriceAwareInterface $entity) |
||
116 | |||
117 | /** |
||
118 | * @return array |
||
119 | */ |
||
120 | public function get() |
||
124 | |||
125 | /** |
||
126 | * @return int |
||
127 | */ |
||
128 | public function total() |
||
137 | |||
138 | /** |
||
139 | * @param \Cart\Storage\StorageInterface $storage |
||
140 | * @return \Cart\Storage\StorageInterface |
||
141 | */ |
||
142 | public function storage(\Cart\Storage\StorageInterface $storage = null) |
||
150 | |||
151 | /** |
||
152 | * @param $entity |
||
153 | * @param $quantity |
||
154 | * @throws \Exception |
||
155 | */ |
||
156 | protected function _validate($entity, $quantity) |
||
165 | |||
166 | /** |
||
167 | * @param $entity |
||
168 | * @throws \Exception |
||
169 | */ |
||
170 | protected function _entityExists($entity) |
||
178 | |||
179 | } |
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.