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 |
||
23 | class ObjectStateToken implements TokenInterface |
||
24 | { |
||
25 | private $name; |
||
26 | private $value; |
||
27 | private $util; |
||
28 | private $comparatorFactory; |
||
29 | |||
30 | /** |
||
31 | * Initializes token. |
||
32 | * |
||
33 | * @param string $methodName |
||
34 | * @param mixed $value Expected return value |
||
35 | * @param null|StringUtil $util |
||
36 | * @param ComparatorFactory $comparatorFactory |
||
37 | */ |
||
38 | View Code Duplication | public function __construct( |
|
50 | |||
51 | /** |
||
52 | * Scores 8 if argument is an object, which method returns expected value. |
||
53 | * |
||
54 | * @param mixed $argument |
||
55 | * |
||
56 | * @return bool|int |
||
57 | */ |
||
58 | public function scoreArgument($argument) |
||
59 | { |
||
60 | if (is_object($argument) && method_exists($argument, $this->name)) { |
||
61 | $actual = call_user_func(array($argument, $this->name)); |
||
62 | |||
63 | $comparator = $this->comparatorFactory->getComparatorFor( |
||
64 | $this->value, $actual |
||
65 | ); |
||
66 | |||
67 | try { |
||
68 | $comparator->assertEquals($this->value, $actual); |
||
69 | return 8; |
||
70 | } catch (ComparisonFailure $failure) { |
||
71 | return false; |
||
72 | } |
||
73 | } |
||
74 | |||
75 | if (is_object($argument) && property_exists($argument, $this->name)) { |
||
76 | return $argument->{$this->name} === $this->value ? 8 : false; |
||
77 | } |
||
78 | |||
79 | return false; |
||
80 | } |
||
81 | |||
82 | /** |
||
83 | * Returns false. |
||
84 | * |
||
85 | * @return bool |
||
86 | */ |
||
87 | public function isLast() |
||
91 | |||
92 | /** |
||
93 | * Returns string representation for token. |
||
94 | * |
||
95 | * @return string |
||
96 | */ |
||
97 | public function __toString() |
||
104 | } |
||
105 |
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.