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 declare(strict_types=1); |
||
16 | class Group extends OperatorResource implements Creatable, Listable, Retrievable, Updateable, Deletable |
||
17 | { |
||
18 | /** @var string */ |
||
19 | public $domainId; |
||
20 | |||
21 | /** @var string */ |
||
22 | public $id; |
||
23 | |||
24 | /** @var string */ |
||
25 | public $description; |
||
26 | |||
27 | /** @var array */ |
||
28 | public $links; |
||
29 | |||
30 | /** @var string */ |
||
31 | public $name; |
||
32 | |||
33 | protected $aliases = ['domain_id' => 'domainId']; |
||
34 | |||
35 | protected $resourceKey = 'group'; |
||
36 | protected $resourcesKey = 'groups'; |
||
37 | |||
38 | /** |
||
39 | * {@inheritDoc} |
||
40 | * |
||
41 | * @param array $data {@see \OpenStack\Identity\v3\Api::postGroups} |
||
42 | */ |
||
43 | 2 | public function create(array $data): Creatable |
|
48 | |||
49 | /** |
||
50 | * {@inheritDoc} |
||
51 | */ |
||
52 | 1 | public function retrieve() |
|
57 | |||
58 | /** |
||
59 | * {@inheritDoc} |
||
60 | */ |
||
61 | 1 | public function update() |
|
66 | |||
67 | /** |
||
68 | * {@inheritDoc} |
||
69 | */ |
||
70 | 1 | public function delete() |
|
74 | |||
75 | /** |
||
76 | * @param array $options {@see \OpenStack\Identity\v3\Api::getGroupUsers} |
||
77 | * |
||
78 | * @return \Generator |
||
79 | */ |
||
80 | 1 | public function listUsers(array $options = []): \Generator |
|
81 | { |
||
82 | 1 | $options['id'] = $this->id; |
|
83 | 1 | return $this->model(User::class)->enumerate($this->api->getGroupUsers(), $options); |
|
|
|||
84 | } |
||
85 | |||
86 | /** |
||
87 | * @param array $options {@see \OpenStack\Identity\v3\Api::putGroupUser} |
||
88 | */ |
||
89 | 1 | public function addUser(array $options) |
|
93 | |||
94 | /** |
||
95 | * @param array $options {@see \OpenStack\Identity\v3\Api::deleteGroupUser} |
||
96 | */ |
||
97 | 2 | public function removeUser(array $options) |
|
101 | |||
102 | /** |
||
103 | * @param array $options {@see \OpenStack\Identity\v3\Api::headGroupUser} |
||
104 | * |
||
105 | * @return bool |
||
106 | */ |
||
107 | 2 | View Code Duplication | public function checkMembership(array $options): bool |
116 | } |
||
117 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: