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 |
||
10 | class Hex implements Color |
||
11 | { |
||
12 | private string $hex; |
||
|
|||
13 | |||
14 | 22 | public function __construct(string $hex) |
|
15 | { |
||
16 | 22 | if (strlen($hex) !== 6 || !ctype_xdigit($hex)) { |
|
17 | 3 | throw new InvalidArgumentException('Please specify a valid hex. (without the #)'); |
|
18 | } |
||
19 | |||
20 | 19 | $this->hex = $hex; |
|
21 | 19 | } |
|
22 | |||
23 | 19 | public function toString(): string |
|
24 | { |
||
25 | 19 | return sprintf('#%s', $this->hex); |
|
26 | } |
||
27 | } |
||
28 |