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 |
||
14 | trait Generic { |
||
15 | |||
16 | /** |
||
17 | * Checks that the given element is of the given type. |
||
18 | * |
||
19 | * @param NodeElement $element |
||
20 | * The element to check. |
||
21 | * @param string $type |
||
22 | * The expected type. |
||
23 | * |
||
24 | * @throws ExpectationException |
||
25 | * Thrown when the given element is not of the expected type. |
||
26 | */ |
||
27 | public function assertElementType(NodeElement $element, $type) { |
||
32 | |||
33 | /** |
||
34 | * Assert presence of given field on the page. |
||
35 | * |
||
36 | * @Then I should see the field :field |
||
37 | */ |
||
38 | View Code Duplication | public function iShouldSeeTheField($field) { |
|
55 | |||
56 | /** |
||
57 | * Assert absence of given field. |
||
58 | * |
||
59 | * @Then I should not see the field :field |
||
60 | */ |
||
61 | View Code Duplication | public function iShouldNotSeeTheField($field) { |
|
78 | |||
79 | /** |
||
80 | * Visit taxonomy term page given its type and name. |
||
81 | * |
||
82 | * @Given I am visiting the :type term :title |
||
83 | * @Given I visit the :type term :title |
||
84 | */ |
||
85 | public function iAmViewingTheTerm($type, $title) { |
||
88 | |||
89 | /** |
||
90 | * Visit taxonomy term edit page given its type and name. |
||
91 | * |
||
92 | * @Given I am editing the :type term :title |
||
93 | * @Given I edit the :type term :title |
||
94 | */ |
||
95 | public function iAmEditingTheTerm($type, $title) { |
||
98 | |||
99 | /** |
||
100 | * Provides a common step definition callback for node pages. |
||
101 | * |
||
102 | * @param string $op |
||
103 | * The operation being performed: 'view', 'edit', 'delete'. |
||
104 | * @param string $type |
||
105 | * The node type either as id or as label. |
||
106 | * @param string $title |
||
107 | * The node title. |
||
108 | * |
||
109 | * @throws ExpectationException |
||
110 | * When the node does not exist. |
||
111 | */ |
||
112 | protected function visitTermPage($op, $type, $title) { |
||
132 | |||
133 | /** |
||
134 | * Assert first element precedes second one. |
||
135 | * |
||
136 | * @Then :first should precede :second |
||
137 | */ |
||
138 | public function shouldPrecede($first, $second) { |
||
152 | |||
153 | } |
||
154 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.