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 |
||
| 8 | trait ManagesLists |
||
| 9 | { |
||
| 10 | /** |
||
| 11 | * Returns all lists |
||
| 12 | * |
||
| 13 | * @return ContactsList[] |
||
| 14 | */ |
||
| 15 | public function lists() |
||
| 23 | |||
| 24 | /** |
||
| 25 | * Returns list by ID |
||
| 26 | * |
||
| 27 | * @param string $name |
||
| 28 | * |
||
| 29 | * @return ContactsList|null |
||
| 30 | */ |
||
| 31 | public function getList($id) |
||
| 48 | |||
| 49 | /** |
||
| 50 | * Finds list by it's name or URL-safe name |
||
| 51 | * |
||
| 52 | * @param string $name name of list to find |
||
| 53 | * |
||
| 54 | * @return null|ContactsList |
||
| 55 | */ |
||
| 56 | public function findList($name) |
||
| 66 | |||
| 67 | /** |
||
| 68 | * Creates a new list |
||
| 69 | * |
||
| 70 | * @param string $name Name of the list to create |
||
| 71 | * @param string $senderUrl The website URL this list is for. |
||
| 72 | * @param array $params other options to create list |
||
| 73 | * |
||
| 74 | * @return ContactsList |
||
| 75 | */ |
||
| 76 | public function createList($name, $senderUrl, $params = []) |
||
| 94 | |||
| 95 | /** |
||
| 96 | * Removes list |
||
| 97 | * |
||
| 98 | * @param int $id ID of the list to delete |
||
| 99 | * |
||
| 100 | * @throws \TestMonitor\ActiveCampaign\Exceptions\NotFoundException |
||
| 101 | */ |
||
| 102 | public function deleteList($id) |
||
| 106 | |||
| 107 | /** |
||
| 108 | * Adds contact to the list |
||
| 109 | * |
||
| 110 | * @param int $contactId ID of contact to add to list |
||
| 111 | * @param int $listId ID of list to add contact to |
||
| 112 | */ |
||
| 113 | View Code Duplication | public function subscribe($contactId, $listId) |
|
| 122 | |||
| 123 | /** |
||
| 124 | * Remove contact from the list |
||
| 125 | * |
||
| 126 | * @param int $contactId ID of contact to remove from list |
||
| 127 | * @param int $listId ID of list to remove contact from |
||
| 128 | */ |
||
| 129 | View Code Duplication | public function unsubscribe($contactId, $listId) |
|
| 138 | |||
| 139 | /** |
||
| 140 | * Get all contacts related to the list. |
||
| 141 | * |
||
| 142 | * @return Contact[] |
||
| 143 | */ |
||
| 144 | public function contactsByList($listId) |
||
| 152 | } |
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
Idableprovides a methodequalsIdthat 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.