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 |
||
22 | class RootUnit implements UnitInterface |
||
23 | { |
||
24 | /** |
||
25 | * @var TreeConverter |
||
26 | */ |
||
27 | protected $tree; |
||
28 | |||
29 | /** |
||
30 | * @var string |
||
31 | */ |
||
32 | protected $name; |
||
33 | |||
34 | /** |
||
35 | * {@inheritdoc} |
||
36 | */ |
||
37 | 9 | public function getName() |
|
41 | |||
42 | 1 | public function getParent() |
|
43 | { |
||
44 | 1 | return $this; |
|
45 | } |
||
46 | |||
47 | 1 | public function getRoot() |
|
51 | |||
52 | public function getFactor() |
||
56 | |||
57 | public function getMeasure() |
||
61 | |||
62 | /** |
||
63 | * @param TreeConverter $tree |
||
64 | * @param string $name |
||
65 | */ |
||
66 | 4 | public function __construct(TreeConverter $tree, $name) |
|
71 | |||
72 | protected $calculator; |
||
73 | |||
74 | /** |
||
75 | * Returns calculator for this unit. |
||
76 | * Units can have different calculators. |
||
77 | * @return CalculatorInterface |
||
78 | */ |
||
79 | 6 | public function getCalculator() |
|
80 | { |
||
81 | 6 | if ($this->calculator === null) { |
|
82 | 2 | $this->calculator = new PhpCalculator(); |
|
83 | 2 | } |
|
84 | |||
85 | 6 | return $this->calculator; |
|
86 | } |
||
87 | |||
88 | /** |
||
89 | * {@inheritdoc} |
||
90 | */ |
||
91 | 7 | public function equals(UnitInterface $other) |
|
95 | |||
96 | 7 | public function isAlias(UnitInterface $other) |
|
102 | |||
103 | 6 | public function getCanon() |
|
107 | |||
108 | /** |
||
109 | * {@inheritdoc} |
||
110 | */ |
||
111 | public function assertConvertible(UnitInterface $other) |
||
117 | |||
118 | /** |
||
119 | * {@inheritdoc} |
||
120 | */ |
||
121 | 2 | final public function isConvertible(UnitInterface $other) |
|
125 | |||
126 | /** |
||
127 | * {@inheritdoc} |
||
128 | */ |
||
129 | 6 | public function convert(UnitInterface $other, $quantity) |
|
147 | |||
148 | 6 | View Code Duplication | public function multiplyByFactor($quantity) |
156 | |||
157 | 5 | View Code Duplication | public function divideByFactor($quantity) |
165 | |||
166 | 7 | public function getNode(UnitInterface $unit) |
|
170 | } |
||
171 |
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: