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 |
||
17 | class EntityEvents |
||
18 | { |
||
19 | |||
20 | /** |
||
21 | * Holds the events. |
||
22 | * @var array |
||
23 | */ |
||
24 | protected $events; |
||
25 | |||
26 | /** |
||
27 | * Executes the event chain of an entity. |
||
28 | * |
||
29 | * @param Entity $entity |
||
30 | * the entity having the event chain to execute |
||
31 | * @param string $moment |
||
32 | * the "moment" of the event, can be either "before" or "after" |
||
33 | * @param string $action |
||
34 | * the "action" of the event, can be either "create", "update" or "delete" |
||
35 | * |
||
36 | * @return boolean |
||
37 | * true on successful execution of the full chain or false if it broke at |
||
38 | * any point (and stopped the execution) |
||
39 | */ |
||
40 | 1 | View Code Duplication | public function shouldExecuteEvents(Entity $entity, $moment, $action) |
53 | |||
54 | /** |
||
55 | * Adds an event to fire for the given parameters. The event function must |
||
56 | * have this signature: |
||
57 | * function (Entity $entity) |
||
58 | * and has to return true or false. |
||
59 | * The events are executed one after another in the added order as long as |
||
60 | * they return "true". The first event returning "false" will stop the |
||
61 | * process. |
||
62 | * |
||
63 | * @param string $moment |
||
64 | * the "moment" of the event, can be either "before" or "after" |
||
65 | * @param string $action |
||
66 | * the "action" of the event, can be either "create", "update" or "delete" |
||
67 | * @param \Closure $function |
||
68 | * the event function to be called if set |
||
69 | */ |
||
70 | 2 | public function pushEvent($moment, $action, \Closure $function) |
|
76 | |||
77 | /** |
||
78 | * Removes and returns the latest event for the given parameters. |
||
79 | * |
||
80 | * @param string $moment |
||
81 | * the "moment" of the event, can be either "before" or "after" |
||
82 | * @param string $action |
||
83 | * the "action" of the event, can be either "create", "update" or "delete" |
||
84 | * |
||
85 | * @return \Closure|null |
||
86 | * the popped event or null if no event was available. |
||
87 | */ |
||
88 | 1 | View Code Duplication | public function popEvent($moment, $action) |
95 | } |
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.