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 Time |
||
| 6 | { |
||
| 7 | |||
| 8 | protected $_value = null; |
||
| 9 | protected $_parts = null; |
||
| 10 | protected $_seconds = null; |
||
| 11 | |||
| 12 | public static function fromString($string) |
||
| 20 | |||
| 21 | public function parseSeconds() |
||
| 32 | |||
| 33 | public function getParts() |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @param array $parts |
||
| 44 | */ |
||
| 45 | public function setParts($parts) |
||
| 49 | |||
| 50 | public function parseParts() |
||
| 58 | |||
| 59 | public function parsePartsFromString() |
||
| 67 | |||
| 68 | /** |
||
| 69 | * @param string $v |
||
| 70 | */ |
||
| 71 | public function setHoursPart($v) |
||
| 75 | |||
| 76 | /** |
||
| 77 | * @param string $p |
||
| 78 | * @param string $v |
||
| 79 | */ |
||
| 80 | public function setPart($p, $v) |
||
| 84 | |||
| 85 | /** |
||
| 86 | * @param string $v |
||
| 87 | */ |
||
| 88 | public function setMinutesPart($v) |
||
| 92 | |||
| 93 | /** |
||
| 94 | * @param string $v |
||
| 95 | */ |
||
| 96 | public function setSecondsPart($v) |
||
| 100 | |||
| 101 | public function parsePartsFromSeconds() |
||
| 120 | |||
| 121 | public function getSeconds() |
||
| 129 | |||
| 130 | /** |
||
| 131 | * @param null $seconds |
||
| 132 | */ |
||
| 133 | public function setSeconds($seconds) |
||
| 137 | |||
| 138 | public static function fromSeconds($seconds) |
||
| 145 | |||
| 146 | public function getFormatedString() |
||
| 167 | |||
| 168 | public function getHoursPart() |
||
| 172 | |||
| 173 | public function getPart($p) |
||
| 181 | |||
| 182 | public function getMinutesPart() |
||
| 186 | |||
| 187 | public function getSecondsPart() |
||
| 191 | |||
| 192 | public function getDefaultString() |
||
| 200 | } |
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
dieintroduces 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 withthrowat this point:These limitations lead to logical operators rarely being of use in current PHP code.