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 |
||
11 | final class Ints |
||
12 | { |
||
13 | /** |
||
14 | * Filters $value to an integer strictly. |
||
15 | * |
||
16 | * $value must be an int or contain all digits, optionally prepended by a '+' or '-' and optionally surrounded by |
||
17 | * whitespace to pass the filter. |
||
18 | * |
||
19 | * The return value is the int, as expected by the \DominionEnterprises\Filterer class. |
||
20 | * |
||
21 | * @param string|int $value the value to make an integer |
||
22 | * @param bool $allowNull Set to true if NULL values are allowed. The filtered result of a NULL value is NULL |
||
23 | * @param int $minValue The minimum acceptable value |
||
24 | * @param int $maxValue The maximum acceptable value |
||
25 | * |
||
26 | * @return int|null The filtered value |
||
27 | * |
||
28 | * @throws \InvalidArgumentException if $allowNull is not a boolean |
||
29 | * @throws \InvalidArgumentException if $minValue is not null and not an int |
||
30 | * @throws \InvalidArgumentException if $maxValue is not an int |
||
31 | * @throws \Exception if $value string length is zero |
||
32 | * @throws \Exception if $value does not contain all digits, optionally prepended by a '+' or '-' and optionally |
||
33 | * surrounded by whitespace |
||
34 | * @throws \Exception if $value was greater than a max int of PHP_INT_MAX |
||
35 | * @throws \Exception if $value was less than a min int of ~PHP_INT_MAX |
||
36 | * @throws \Exception if $value is not a string |
||
37 | * @throws \Exception if $value is less than $minValue |
||
38 | * @throws \Exception if $value is greater than $maxValue |
||
39 | */ |
||
40 | public static function filter($value, $allowNull = false, $minValue = null, $maxValue = PHP_INT_MAX) |
||
108 | } |
||
109 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.