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 MoneyFormatter |
||
11 | { |
||
12 | /** |
||
13 | * @var |
||
14 | */ |
||
15 | private $locale; |
||
16 | |||
17 | /** |
||
18 | * @param null|string $locale |
||
19 | */ |
||
20 | 18 | public function __construct($locale = null) |
|
21 | { |
||
22 | 18 | $this->locale = $locale; |
|
23 | 18 | if ($this->locale === null) { |
|
24 | 6 | $this->locale = \Locale::getDefault(); |
|
25 | 2 | } |
|
26 | 18 | } |
|
27 | |||
28 | /** |
||
29 | * localized format for money with the NumberFormatter class in Decimal mode |
||
30 | * without currency symbol |
||
31 | * like 1.234,56 |
||
32 | * |
||
33 | * @param Money $money |
||
34 | * @param null $locale |
||
35 | * @return bool|string |
||
36 | */ |
||
37 | 3 | View Code Duplication | public function formatI18nDecimal(Money $money, $locale = null) |
48 | |||
49 | /** |
||
50 | * localized format for money with the NumberFormatter class in Currency mode |
||
51 | * with currency symbol |
||
52 | * like €1.234,56 |
||
53 | * |
||
54 | * @param Money $money |
||
55 | * @param null $locale |
||
56 | * @return bool|string |
||
57 | */ |
||
58 | 9 | View Code Duplication | public function formatI18n(Money $money, $locale = null) |
69 | |||
70 | /** |
||
71 | * gets currency symbol |
||
72 | * |
||
73 | * @param Money $money |
||
74 | * @return null|string |
||
75 | */ |
||
76 | 6 | public function formatCurrencyAsSymbol(Money $money) |
|
80 | |||
81 | /** |
||
82 | * gets currency name |
||
83 | * |
||
84 | * @param Money $money |
||
85 | * @return null|string |
||
86 | */ |
||
87 | 6 | public function formatCurrencyAsName(Money $money) |
|
91 | } |
||
92 |
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.