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 |
||
7 | trait ManagesAccounts |
||
8 | { |
||
9 | use ImplementsActions; |
||
10 | |||
11 | /** |
||
12 | * Get all accounts. |
||
13 | * |
||
14 | * @return array |
||
15 | */ |
||
16 | public function accounts() |
||
24 | |||
25 | /** |
||
26 | * Find account by name. |
||
27 | * |
||
28 | * @param string $name |
||
29 | * |
||
30 | * @return Account|null |
||
31 | */ |
||
32 | public function findAccount($name) |
||
42 | |||
43 | /** |
||
44 | * Create new account. |
||
45 | * |
||
46 | * @param array $data |
||
47 | * |
||
48 | * @return Account|null |
||
49 | */ |
||
50 | public function createAccount(array $data = []) |
||
59 | |||
60 | /** |
||
61 | * Update an account. |
||
62 | * |
||
63 | * @param int $accountId |
||
64 | * @param array $data |
||
65 | * |
||
66 | * @return Account|null |
||
67 | */ |
||
68 | public function updateAccount($accountId, array $data = []) |
||
77 | |||
78 | /** |
||
79 | * Find or create an account. |
||
80 | * |
||
81 | * @param string $name |
||
82 | * @param array $data |
||
83 | * |
||
84 | * @return Account |
||
85 | */ |
||
86 | View Code Duplication | public function findOrCreateAccount($name, array $data = []) |
|
100 | |||
101 | /** |
||
102 | * Update or create an account. |
||
103 | * |
||
104 | * @param string $name |
||
105 | * @param array $data |
||
106 | * |
||
107 | * @return Account |
||
108 | */ |
||
109 | View Code Duplication | public function updateOrCreateAccount($name, array $data = []) |
|
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.