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 |
||
16 | class AppConfig{ |
||
17 | private $appName = 'documents'; |
||
18 | private $defaults = [ |
||
19 | 'converter' => 'off', |
||
20 | 'converter_url' => 'http://localhost:16080', |
||
21 | 'unstable' => 'false' |
||
22 | ]; |
||
23 | |||
24 | private $config; |
||
25 | |||
26 | public function __construct(IConfig $config) { |
||
29 | |||
30 | /** |
||
31 | * Can we convert anything to odt? |
||
32 | * @return bool |
||
33 | */ |
||
34 | public function isConverterEnabled(){ |
||
37 | |||
38 | /** |
||
39 | * Get a value by key |
||
40 | * @param string $key |
||
41 | * @return string |
||
42 | */ |
||
43 | View Code Duplication | public function getAppValue($key) { |
|
|
|||
44 | $defaultValue = null; |
||
45 | if (array_key_exists($key, $this->defaults)){ |
||
46 | $defaultValue = $this->defaults[$key]; |
||
47 | } |
||
48 | return $this->config->getAppValue($this->appName, $key, $defaultValue); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * Set a value by key |
||
53 | * @param string $key |
||
54 | * @param string $value |
||
55 | * @return string |
||
56 | */ |
||
57 | public function setAppValue($key, $value) { |
||
60 | |||
61 | /** |
||
62 | * Get a value by key for a user |
||
63 | * @param string $userId |
||
64 | * @param string $key |
||
65 | * @return string |
||
66 | */ |
||
67 | View Code Duplication | public function getUserValue($userId, $key) { |
|
68 | $defaultValue = null; |
||
69 | if (array_key_exists($key, $this->defaults)){ |
||
70 | $defaultValue = $this->defaults[$key]; |
||
71 | } |
||
72 | return $this->config->getUserValue($userId, $this->appName, $key, $defaultValue); |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * Set a value by key for a user |
||
77 | * @param string $userId |
||
78 | * @param string $key |
||
79 | * @param string $value |
||
80 | * @return string |
||
81 | */ |
||
82 | public function setUserValue($userId, $key, $value) { |
||
85 | } |
||
86 |
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.