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 | class EventBus { |
||
| 15 | |||
| 16 | /** |
||
| 17 | * @var IObserver[][] $subscriptions |
||
| 18 | */ |
||
| 19 | protected $subscriptions; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var GlobalContainer $gc |
||
| 23 | */ |
||
| 24 | protected $gc; |
||
| 25 | |||
| 26 | public function __construct(GlobalContainer $gc) { |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @param IObserver $observer |
||
| 32 | * @param int $eventId |
||
| 33 | * |
||
| 34 | * @return bool|mixed - false if observer not subscribed to event or observer subscription ID |
||
| 35 | */ |
||
| 36 | public function haveSubscription(IObserver $observer, $eventId) { |
||
| 43 | |||
| 44 | protected function unSubscribeFromOne(IObserver $observer, $eventId) { |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Unsubscribes observer from all events |
||
| 52 | * |
||
| 53 | * @param IObserver $observer |
||
| 54 | */ |
||
| 55 | protected function unSubscribeFromAll(IObserver $observer) { |
||
| 60 | |||
| 61 | |||
| 62 | public function subscribe(IObserver $observer, $eventId = EVENT_ALL) { |
||
| 74 | |||
| 75 | public function unSubscribe($observer, $eventId = EVENT_ALL) { |
||
| 82 | |||
| 83 | public function dispatch(Event $event) { |
||
| 99 | |||
| 100 | /** |
||
| 101 | * @param IObserver[] $typeSubscriptions |
||
| 102 | * |
||
| 103 | * @return IObserver[] |
||
| 104 | */ |
||
| 105 | protected function mergeEventAllObservers($typeSubscriptions) { |
||
| 115 | |||
| 116 | } |
||
| 117 |
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.