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 Rgb implements Color |
||
| 6 | { |
||
| 7 | /** @var int */ |
||
| 8 | protected $red, $green, $blue; |
||
|
|
|||
| 9 | |||
| 10 | View Code Duplication | public function __construct(int $red, int $green, int $blue) |
|
| 20 | |||
| 21 | View Code Duplication | public static function fromString(string $string) |
|
| 22 | { |
||
| 23 | Validate::rgbColorString($string); |
||
| 24 | |||
| 25 | $matches = null; |
||
| 26 | preg_match('/rgb\((\d{1,3},\d{1,3},\d{1,3})\)/i', $string, $matches); |
||
| 27 | |||
| 28 | list($red, $green, $blue) = explode(',', $matches[1]); |
||
| 29 | |||
| 30 | return new static($red, $green, $blue); |
||
| 31 | } |
||
| 32 | |||
| 33 | public function red(): int |
||
| 37 | |||
| 38 | public function green(): int |
||
| 42 | |||
| 43 | public function blue(): int |
||
| 47 | |||
| 48 | public function toHex(): Hex |
||
| 56 | |||
| 57 | public function toRgb(): Rgb |
||
| 61 | |||
| 62 | public function toRgba(float $alpha = 1): Rgba |
||
| 66 | |||
| 67 | public function __toString(): string |
||
| 71 | } |
||
| 72 |
Only declaring a single property per statement allows you to later on add doc comments more easily.
It is also recommended by PSR2, so it is a common style that many people expect.