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 LineKey |
||
8 | { |
||
9 | private $key; |
||
10 | |||
11 | 69 | public function __construct($key) |
|
17 | |||
18 | public static function fromString($key) |
||
19 | { |
||
20 | return new self($key); |
||
21 | } |
||
22 | |||
23 | 51 | public function get() |
|
27 | |||
28 | /** |
||
29 | * Get suggestion for a label based on the key |
||
30 | * |
||
31 | * @return string |
||
32 | */ |
||
33 | 51 | public function getAsLabel() |
|
34 | { |
||
35 | // Remove first part since that part equals the page |
||
36 | 51 | $key = substr($this->key, strpos($this->key, '.')+1); |
|
37 | |||
38 | 51 | $label = str_replace('.', ' ', $key); |
|
39 | |||
40 | 51 | return ucfirst($label); |
|
41 | } |
||
42 | |||
43 | /** |
||
44 | * Get Page identifier. |
||
45 | * This is the first segment of the key |
||
46 | * |
||
47 | * @return string |
||
48 | */ |
||
49 | 57 | public function getPageKey() |
|
53 | |||
54 | 63 | private function sanitizeKey($key) |
|
55 | { |
||
56 | 63 | return strtolower($key); |
|
57 | } |
||
58 | |||
59 | 69 | private function validateKey($key) |
|
65 | |||
66 | } |
||
67 |
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.