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 | class ExperienceSubscriber |
||
11 | { |
||
12 | |||
13 | /** |
||
14 | * The experience earned for the related event. |
||
15 | * |
||
16 | * @var array |
||
17 | */ |
||
18 | protected $experiences = [ |
||
19 | PostWasSolvedEvent::class => 120, |
||
20 | ConversationWasCreatedEvent::class => 90, |
||
21 | PostWasCreatedEvent::class => 75 |
||
22 | ]; |
||
23 | |||
24 | /** |
||
25 | * The events mapping to the listener function. |
||
26 | * |
||
27 | * @var array |
||
28 | */ |
||
29 | protected $events = [ |
||
30 | PostWasCreatedEvent::class => 'postWasCreated', |
||
31 | PostWasSolvedEvent::class => 'postWasSolved', |
||
32 | ConversationWasCreatedEvent::class => 'conversationWasCreated' |
||
33 | ]; |
||
34 | |||
35 | /** |
||
36 | * Register the listeners for the subscriber. |
||
37 | * |
||
38 | * @param Illuminate\Events\Dispatcher $events |
||
39 | * |
||
40 | * @return void |
||
41 | */ |
||
42 | public function subscribe($events) |
||
48 | |||
49 | /** |
||
50 | * Handle a PostWasCreated event. |
||
51 | * |
||
52 | * @param \Xetaravel\Events\Experiences\PostWasCreatedEvent $event The event that was fired. |
||
53 | * |
||
54 | * @return bool |
||
55 | */ |
||
56 | public function postWasCreated(PostWasCreatedEvent $event) |
||
67 | |||
68 | /** |
||
69 | * Handle a PostWasSolved event. |
||
70 | * |
||
71 | * @param \Xetaravel\Events\Experiences\PostWasSolvedEvent $event The event that was fired. |
||
72 | * |
||
73 | * @return bool |
||
74 | */ |
||
75 | View Code Duplication | public function postWasSolved(PostWasSolvedEvent $event) |
|
87 | |||
88 | /** |
||
89 | * Handle a ConversationWasCreated event. |
||
90 | * |
||
91 | * @param \Xetaravel\Events\Experiences\ConversationWasCreatedEvent $event The event that was fired. |
||
92 | * |
||
93 | * @return bool |
||
94 | */ |
||
95 | View Code Duplication | public function conversationWasCreated(ConversationWasCreatedEvent $event) |
|
106 | |||
107 | /** |
||
108 | * Create the experience. |
||
109 | * |
||
110 | * @param array $data The data used to create the experience. |
||
111 | * |
||
112 | * @return bool |
||
113 | */ |
||
114 | protected function create(array $data) : bool |
||
123 | } |
||
124 |
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.