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 |
||
5 | class ConnectedDifferences |
||
6 | { |
||
7 | /** |
||
8 | * @var array |
||
9 | */ |
||
10 | private $bitmap; |
||
11 | |||
12 | /** |
||
13 | * @var int |
||
14 | */ |
||
15 | private $width; |
||
16 | |||
17 | /** |
||
18 | * @var int |
||
19 | */ |
||
20 | private $height; |
||
21 | |||
22 | /** |
||
23 | * @var array |
||
24 | */ |
||
25 | private $boundaries = []; |
||
26 | |||
27 | /** |
||
28 | * @param Difference $difference |
||
29 | */ |
||
30 | public function __construct(Difference $difference) |
||
38 | |||
39 | /** |
||
40 | * Find separate boundaries. |
||
41 | * |
||
42 | * @return array |
||
43 | */ |
||
44 | private function findBoundaries() |
||
130 | |||
131 | /** |
||
132 | * @return ConnectedDifferences |
||
133 | */ |
||
134 | public function withJoinedBoundaries() |
||
166 | |||
167 | /** |
||
168 | * @param string $property |
||
169 | * @param mixed $value |
||
170 | * |
||
171 | * @return ConnectedDifferences |
||
172 | */ |
||
173 | private function cloneWith($property, $value) |
||
180 | |||
181 | /** |
||
182 | * Labels for adjacent pixels. |
||
183 | * |
||
184 | * @param array $pixel |
||
185 | * |
||
186 | * @return array |
||
187 | */ |
||
188 | private function adjacent($pixel) |
||
202 | |||
203 | /** |
||
204 | * Tell if two boundaries overlap. |
||
205 | * |
||
206 | * @param array $p |
||
207 | * @param array $q |
||
208 | * |
||
209 | * @return bool |
||
210 | */ |
||
211 | private function intersect(array $p, array $q) |
||
215 | |||
216 | /** |
||
217 | * @return array |
||
218 | */ |
||
219 | public function boundaries() |
||
223 | } |
||
224 |
PHP has two types of connecting operators (logical operators, and boolean operators):
and
&&
or
||
The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like
&&
, or||
.Let’s take a look at a few examples:
Logical Operators are used for Control-Flow
One case where you explicitly want to use logical operators is for control-flow such as this:
Since
die
introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined withthrow
at this point:These limitations lead to logical operators rarely being of use in current PHP code.