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 namespace GenericCollections\Abstracts; |
||
8 | abstract class AbstractMap extends InternalDataArray implements MapInterface, \ArrayAccess |
||
9 | { |
||
10 | public function checkValueType($value) |
||
14 | |||
15 | public function checkKeyType($key) |
||
19 | |||
20 | public function containsKey($key) |
||
24 | |||
25 | public function containsValue($value) |
||
29 | |||
30 | public function get($key) |
||
34 | |||
35 | public function getOrDefault($key, $default) |
||
36 | { |
||
37 | if ($this->containsKey($key)) { |
||
38 | return $this->data[$key]; |
||
39 | } |
||
40 | if (null !== $default and ! $this->checkValueType($default)) { |
||
41 | throw new \InvalidArgumentException( |
||
42 | 'The default value provided for ' |
||
43 | . get_class($this) . '::getOrDefault is not a valid type,' |
||
44 | . ' expected ' . $this->getKeyType() . '.' |
||
45 | ); |
||
46 | } |
||
47 | return $default; |
||
48 | } |
||
49 | |||
50 | public function keys() |
||
54 | |||
55 | public function put($key, $value) |
||
75 | |||
76 | public function putAll(array $values) |
||
82 | |||
83 | public function putIfAbsent($key, $value) |
||
92 | |||
93 | public function remove($key) |
||
101 | |||
102 | public function removeExact($key, $value) |
||
115 | |||
116 | public function replace($key, $value) |
||
120 | |||
121 | public function replaceExact($key, $current, $replacement) |
||
136 | |||
137 | public function keysSet() |
||
141 | |||
142 | public function valuesCollection() |
||
146 | |||
147 | |||
148 | |||
149 | /* |
||
150 | * Implementations from \ArrayAccess |
||
151 | */ |
||
152 | /** @inheritdoc */ |
||
153 | public function offsetExists($offset) |
||
157 | |||
158 | /** @inheritdoc */ |
||
159 | public function offsetGet($offset) |
||
163 | |||
164 | /** @inheritdoc */ |
||
165 | public function offsetSet($offset, $value) |
||
169 | |||
170 | /** @inheritdoc */ |
||
171 | public function offsetUnset($offset) |
||
175 | } |
||
176 |
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.