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 |
||
10 | class Currency extends Number implements NumberInterface, DecimalInterface |
||
11 | { |
||
12 | const DOLLAR = '$'; |
||
13 | const EURO = '€'; |
||
14 | const POUND = '£'; |
||
15 | const YUAN = '¥'; |
||
16 | const YEN = '¥'; |
||
17 | const WON = '₩'; |
||
18 | const RUBLE = '₽'; |
||
19 | const RIYAL = '﷼'; |
||
20 | const RUPEE_INDIA = '₹'; |
||
21 | |||
22 | protected $symbol; |
||
23 | |||
24 | public function __construct($value, $symbol = Currency::DOLLAR, $precision = null, $base = 10) |
||
30 | |||
31 | public function __toString() |
||
35 | |||
36 | public function modulo($mod) |
||
42 | |||
43 | View Code Duplication | public function continuousModulo($mod) |
|
53 | |||
54 | public function compoundInterest($interest, $periods) |
||
64 | |||
65 | /** |
||
66 | * @param $value |
||
67 | * |
||
68 | * @return Currency |
||
69 | */ |
||
70 | protected function setValue($value) |
||
74 | |||
75 | } |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: