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 | trait ModelEditing |
||
11 | { |
||
12 | /** |
||
13 | * Method fired before the Edit action is undertaken. |
||
14 | * |
||
15 | * @return |
||
16 | */ |
||
17 | protected function beforeEdit() |
||
20 | |||
21 | /** |
||
22 | * Edit Action. |
||
23 | * |
||
24 | * Fires off beforeEdit(), doEdit() and afterEdit() |
||
25 | * |
||
26 | * @param int $modelitemId |
||
27 | * |
||
28 | * @return |
||
29 | */ |
||
30 | public function edit($modelitemId) |
||
44 | |||
45 | /** |
||
46 | * The actual Edit action, which does all of the pre-processing |
||
47 | * required before we are able to perform the save() function. |
||
48 | * |
||
49 | * @return |
||
50 | */ |
||
51 | View Code Duplication | private function doEdit() |
|
63 | |||
64 | /** |
||
65 | * Method fired after the Edit action is complete. |
||
66 | * |
||
67 | * @return |
||
68 | */ |
||
69 | protected function afterEdit() |
||
72 | } |
||
73 |
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.