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 Utils |
||
| 6 | { |
||
| 7 | /** |
||
| 8 | * Clamps a number between a minimum and a maximum value. |
||
| 9 | * @param int|float $n the number to clamp |
||
| 10 | * @param int|float $min the lower end number allowed |
||
| 11 | * @param int|float $max the higher end number allowed |
||
| 12 | * @return int|float |
||
| 13 | */ |
||
| 14 | public static function clampNumber($n, $min, $max) |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Clamps a RGB color number outside the sRGB color space |
||
| 21 | * @param int|float $n the number to clamp |
||
| 22 | * @return int|float |
||
| 23 | */ |
||
| 24 | public static function clampNumberSrgb($n) |
||
| 28 | |||
| 29 | /** |
||
| 30 | * Converts a HSL color into a RGB color |
||
| 31 | * @param array $hslValues |
||
| 32 | * @return array |
||
| 33 | */ |
||
| 34 | public static function hslToRgb($hslValues) |
||
| 57 | |||
| 58 | /** |
||
| 59 | * Tests and selects the correct formula for each RGB color channel |
||
| 60 | * @param $v1 |
||
| 61 | * @param $v2 |
||
| 62 | * @param $vh |
||
| 63 | * @return mixed |
||
| 64 | */ |
||
| 65 | public static function hueToRgb($v1, $v2, $vh) |
||
| 83 | |||
| 84 | /** |
||
| 85 | * Convert strings like "64M" or "30" to int values |
||
| 86 | * @param mixed $size |
||
| 87 | * @return int |
||
| 88 | */ |
||
| 89 | public static function normalizeInt($size) |
||
| 108 | |||
| 109 | /** |
||
| 110 | * Converts a string containing and RGB percentage value into a RGB integer value i.e. '90%' -> 229.5 |
||
| 111 | * @param $rgbPercentage |
||
| 112 | * @return int |
||
| 113 | */ |
||
| 114 | public static function rgbPercentageToRgbInteger($rgbPercentage) |
||
| 122 | |||
| 123 | /** |
||
| 124 | * Converts a RGB color into a HEX color |
||
| 125 | * @param array $rgbColors |
||
| 126 | * @return array |
||
| 127 | */ |
||
| 128 | public static function rgbToHex($rgbColors) |
||
| 139 | |||
| 140 | /** |
||
| 141 | * Rounds a number to its closest integer |
||
| 142 | * @param $n |
||
| 143 | * @return int |
||
| 144 | */ |
||
| 145 | public static function roundNumber($n) |
||
| 149 | } |
||
| 150 |
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.