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 PreciseMoney extends Money |
||
8 | { |
||
9 | const CALCULATION_SCALE = 10; |
||
10 | |||
11 | public function __construct(float $amount = 0) |
||
15 | |||
16 | public function add(Money $operand): Money |
||
22 | |||
23 | public function subtract(Money $operand): Money |
||
29 | |||
30 | public function multiply(float $multiplier): Money |
||
36 | |||
37 | public function divide(float $divisor): Money |
||
43 | |||
44 | View Code Duplication | public function getPercentage(float $percentage): Money |
|
51 | |||
52 | public function applyPercentage(float $percentage): Money |
||
58 | |||
59 | View Code Duplication | public function getInterest(float $rate, int $duration): Money |
|
74 | |||
75 | public function applyInterest(float $rate, int $duration): Money |
||
81 | |||
82 | public function equals($other): bool |
||
90 | |||
91 | public function greaterThan(Money $other): bool |
||
95 | |||
96 | public function lessThan(Money $other): bool |
||
100 | |||
101 | public function getMoneyAmount(): float |
||
107 | |||
108 | public function getAmount(): int |
||
112 | |||
113 | public function setAmount(float $amount) |
||
117 | } |
||
118 |
This check looks for assignments to scalar types that may be of the wrong type.
To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.