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 |
||
12 | class ItemBasket implements \IteratorAggregate |
||
13 | { |
||
14 | /** |
||
15 | * @var ItemEnvelope[] Contained items |
||
16 | */ |
||
17 | private $items = []; |
||
18 | |||
19 | /** |
||
20 | * Optionally load items at construct |
||
21 | */ |
||
22 | 24 | public function __construct(ItemEnvelope ...$items) { |
|
27 | |||
28 | /** |
||
29 | * Add item to basket |
||
30 | */ |
||
31 | 8 | public function addItem(ItemEnvelope $item): self |
|
36 | |||
37 | /** |
||
38 | * Get contained items |
||
39 | * |
||
40 | * @return ItemEnvelope[] |
||
41 | */ |
||
42 | 7 | public function getItems(): array |
|
46 | |||
47 | /** |
||
48 | * Implements the IteratorAggregate interface |
||
49 | */ |
||
50 | 1 | public function getIterator(): \Traversable |
|
56 | |||
57 | /** |
||
58 | * Get number of items in basket |
||
59 | */ |
||
60 | 1 | public function getNrOfItems(): int |
|
64 | |||
65 | /** |
||
66 | * Get number of units in basket (each item may contain multiple units) |
||
67 | */ |
||
68 | 1 | public function getNrOfUnits(): int |
|
78 | |||
79 | /** |
||
80 | * Get total cost of all items (VAT excluded) |
||
81 | */ |
||
82 | 3 | View Code Duplication | public function getTotalUnitCost(): Amount |
92 | |||
93 | /** |
||
94 | * Get total VAT cost for all items |
||
95 | */ |
||
96 | 3 | View Code Duplication | public function getTotalVatCost(): Amount |
106 | |||
107 | /** |
||
108 | * Get total cost of all items (VAT included) |
||
109 | */ |
||
110 | 2 | public function getTotalCost(): Amount |
|
114 | |||
115 | /** |
||
116 | * Get charged vat amounts for non-zero vat rates |
||
117 | * |
||
118 | * @return Billable[] |
||
119 | */ |
||
120 | 1 | public function getVatRates(): array |
|
145 | } |
||
146 |
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.