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 Guzzle6Adapter implements AdapterInterface |
||
23 | { |
||
24 | /** |
||
25 | * @var Client |
||
26 | */ |
||
27 | protected $client; |
||
28 | |||
29 | 102 | protected $logger; |
|
30 | |||
31 | 102 | public function __construct(array $options = []) |
|
45 | |||
46 | 40 | public function setLogger(LoggerInterface $logger) |
|
51 | |||
52 | 40 | /** |
|
53 | 40 | * Middleware that logs requests, responses, and errors using a message |
|
54 | * formatter. |
||
55 | * |
||
56 | * @param LoggerInterface $logger Logs messages. |
||
57 | * @param MessageFormatter $formatter Formatter used to create message strings. |
||
58 | * @param string $logLevel Level at which to log requests. |
||
59 | 446 | * |
|
60 | * @return callable Returns a function that accepts the next handler. |
||
61 | */ |
||
62 | 446 | private static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO) |
|
92 | |||
93 | 308 | public function addHandler($handler) |
|
97 | |||
98 | /** |
||
99 | * @param RequestInterface $request |
||
100 | * @return ResponseInterface |
||
101 | */ |
||
102 | public function execute(RequestInterface $request) |
||
113 | 3 | ||
114 | /** |
||
115 | 41 | * @param RequestInterface[] $requests |
|
116 | * @return ResponseInterface[] |
||
117 | */ |
||
118 | public function executeBatch(array $requests) |
||
138 | |||
139 | /** |
||
140 | * @param $oauthUri |
||
141 | * @param $clientId |
||
142 | * @param $clientSecret |
||
143 | * @param $formParams |
||
144 | * @return ResponseInterface |
||
145 | */ |
||
146 | public function authenticate($oauthUri, $clientId, $clientSecret, $formParams) |
||
160 | |||
161 | /** |
||
162 | * @param RequestInterface $request |
||
163 | * @return AdapterPromiseInterface |
||
164 | */ |
||
165 | public function executeAsync(RequestInterface $request) |
||
171 | } |
||
172 |
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.