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 |
||
21 | class EntriesBinding extends AbstractBinding |
||
22 | { |
||
23 | use EntriesBindingTrait, LogsBindingTrait, UsersBindingTrait; |
||
24 | |||
25 | const SCOPE_COUNT = 'count'; |
||
26 | |||
27 | const INCLUDE_USER = 'user'; |
||
28 | const INCLUDE_LOG = 'log'; |
||
29 | |||
30 | /** |
||
31 | * Constuct an entries binding from a database connector |
||
32 | * |
||
33 | * @param PDO $database |
||
34 | * |
||
35 | * @throws BindingException |
||
36 | */ |
||
37 | public function __construct(PDO $database) |
||
41 | |||
42 | /** |
||
43 | * Retrieve an entry by ID |
||
44 | * |
||
45 | * By default, entries contain both log and user sub-objects. |
||
46 | * |
||
47 | * @param int|string $id |
||
48 | * @param array $params |
||
49 | * |
||
50 | * @return Entry|null |
||
51 | */ |
||
52 | public function get($id, $params = [self::SCOPE_INCLUDE => [self::INCLUDE_LOG, self::INCLUDE_USER]]) |
||
56 | |||
57 | /** |
||
58 | * Instantiate an entry retrieved via `get()` |
||
59 | * |
||
60 | * @used-by EntriesBinding::instantiateListedObject() |
||
61 | * |
||
62 | * @param array $databaseRow |
||
63 | * @param array $params |
||
64 | * |
||
65 | * @return Entry |
||
66 | */ |
||
67 | protected function instantiateObject($databaseRow, $params) |
||
82 | |||
83 | /** |
||
84 | * Instantiate an entry retrieved via `all()` |
||
85 | * |
||
86 | * @param array $databaseRow |
||
87 | * @param array $params |
||
88 | * |
||
89 | * @uses EntriesBinding::instantiateObject() |
||
90 | * |
||
91 | * @return Entry |
||
92 | */ |
||
93 | protected function instantiateListedObject($databaseRow, $params) |
||
97 | |||
98 | /** |
||
99 | * Retrieve all entries in a specific log, by log ID |
||
100 | * |
||
101 | * By default, entries retrieved by this method contain user sub-object, but _not_ a log sub-object. |
||
102 | * |
||
103 | * @param integer|string $id Numeric log ID |
||
104 | * @param array $params (Optional) Associative array of additional request parameters |
||
105 | * @return Entry[] |
||
106 | */ |
||
107 | public function listByLog($id, $params = [self::SCOPE_INCLUDE => [self::INCLUDE_USER]]) |
||
126 | } |
||
127 |
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.