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 |
||
18 | class PluginApiService |
||
19 | { |
||
20 | /** |
||
21 | * Url for Api |
||
22 | * |
||
23 | * @var string |
||
24 | */ |
||
25 | private $apiUrl; |
||
26 | |||
27 | /** |
||
28 | * @var EccubeConfig |
||
29 | */ |
||
30 | private $eccubeConfig; |
||
31 | |||
32 | /** |
||
33 | * PluginApiService constructor. |
||
34 | * |
||
35 | * @param EccubeConfig $eccubeConfig |
||
36 | */ |
||
37 | public function __construct(EccubeConfig $eccubeConfig) |
||
41 | |||
42 | /** |
||
43 | * @return mixed |
||
44 | */ |
||
45 | public function getApiUrl() |
||
53 | |||
54 | /** |
||
55 | * @param mixed $apiUrl |
||
56 | */ |
||
57 | public function setApiUrl($apiUrl) |
||
61 | |||
62 | public function getCategory() |
||
68 | |||
69 | public function getPlugins($data = []) |
||
81 | |||
82 | /** |
||
83 | * API request processing |
||
84 | * |
||
85 | * @param string $url |
||
86 | * @param array $data |
||
87 | * |
||
88 | * @return array |
||
89 | */ |
||
90 | public function getRequestApi($url, $data = []) |
||
120 | |||
121 | /** |
||
122 | * Get message |
||
123 | * |
||
124 | * @param $info |
||
125 | * |
||
126 | * @return string |
||
127 | */ |
||
128 | View Code Duplication | public function getResponseErrorMessage($info) |
|
140 | } |
||
141 |
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArray
is initialized the first time when the foreach loop is entered. You can also see that the value of thebar
key is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.