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 |
||
| 7 | class Calculator implements Arrayable |
||
| 8 | { |
||
| 9 | /** |
||
| 10 | * @var float |
||
| 11 | */ |
||
| 12 | public $price; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * @var float |
||
| 16 | */ |
||
| 17 | public $vatRate; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @var float |
||
| 21 | */ |
||
| 22 | public $discount; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @param array $attributes |
||
| 26 | */ |
||
| 27 | View Code Duplication | public function __construct(array $attributes = []) |
|
| 37 | |||
| 38 | /** |
||
| 39 | * @return float |
||
| 40 | */ |
||
| 41 | public function netPrice() |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @return float |
||
| 48 | */ |
||
| 49 | public function grossPrice() |
||
| 53 | |||
| 54 | /** |
||
| 55 | * @return float |
||
| 56 | */ |
||
| 57 | public function vatPrice() |
||
| 61 | |||
| 62 | /** |
||
| 63 | * @return array |
||
| 64 | */ |
||
| 65 | public function toArray() |
||
| 74 | |||
| 75 | /** |
||
| 76 | * @param float $price |
||
| 77 | * @return float |
||
| 78 | */ |
||
| 79 | private function calculateDiscount($price) |
||
| 83 | } |
||
| 84 |
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.