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 |
||
26 | class FocalLength extends StringObject |
||
27 | { |
||
28 | /** |
||
29 | * @param string $stringData |
||
30 | * |
||
31 | * @throws InvalidArgumentException If given argument is not a string |
||
32 | */ |
||
33 | View Code Duplication | public function __construct($stringData) |
|
|
|||
34 | { |
||
35 | if (!is_string($stringData)) { |
||
36 | throw new InvalidArgumentException('Given data is not a string'); |
||
37 | } |
||
38 | |||
39 | if (!preg_match('#^([0-9]+)/([0-9]+)$#', $stringData, $matches)) { |
||
40 | throw new RuntimeException('Given focal length is not in a valid format. Need: "<number>/<number>"'); |
||
41 | } |
||
42 | |||
43 | $numerator = (int) $matches[1]; |
||
44 | $denominator = (int) $matches[2]; |
||
45 | |||
46 | // normalize: |
||
47 | $numerator /= $denominator; |
||
48 | |||
49 | $this->setStringData("{$numerator}mm"); |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Creates new instance with data in milimeter |
||
54 | * |
||
55 | * @param string $stringData |
||
56 | * |
||
57 | * @return FocalLength |
||
58 | */ |
||
59 | public static function fromMM($stringData) |
||
75 | |||
76 | /** |
||
77 | * Creates a new instance from given FocalLength object |
||
78 | * |
||
79 | * @param FocalLength $focalLength |
||
80 | * |
||
81 | * @return FocalLength |
||
82 | */ |
||
83 | public static function fromFocalLength(FocalLength $focalLength) |
||
87 | } |
||
88 |
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.