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); |
||
13 | class Service extends AbstractService |
||
14 | { |
||
15 | /** |
||
16 | * Retrieves an Account object. |
||
17 | * |
||
18 | * @return Account |
||
19 | */ |
||
20 | 1 | public function getAccount(): Account |
|
24 | |||
25 | /** |
||
26 | * Retrieves a collection of container resources in a generator format. |
||
27 | * |
||
28 | * @param array $options {@see \OpenStack\ObjectStore\v1\Api::getAccount} |
||
29 | * @param callable|null $mapFn Allows a function to be mapped over each element in the collection. |
||
30 | * |
||
31 | * @return \Generator |
||
32 | */ |
||
33 | 1 | public function listContainers(array $options = [], callable $mapFn = null): \Generator |
|
34 | { |
||
35 | 1 | $options = array_merge($options, ['format' => 'json']); |
|
36 | 1 | return $this->model(Container::class)->enumerate($this->api->getAccount(), $options, $mapFn); |
|
|
|||
37 | } |
||
38 | |||
39 | /** |
||
40 | * Retrieves a Container object and populates its name according to the value provided. Please note that the |
||
41 | * remote API is not contacted. |
||
42 | * |
||
43 | * @param string $name The unique name of the container |
||
44 | * |
||
45 | * @return Container |
||
46 | */ |
||
47 | 2 | public function getContainer(string $name = null): Container |
|
51 | |||
52 | /** |
||
53 | * Creates a new container according to the values provided. |
||
54 | * |
||
55 | * @param array $data {@see \OpenStack\ObjectStore\v1\Api::putContainer} |
||
56 | * |
||
57 | * @return Container |
||
58 | */ |
||
59 | 2 | public function createContainer(array $data): Container |
|
63 | |||
64 | /** |
||
65 | * Checks the existence of a container. |
||
66 | * |
||
67 | * @param string $name The name of the container |
||
68 | * |
||
69 | * @return bool TRUE if exists, FALSE if it doesn't |
||
70 | * @throws BadResponseError Thrown for any non 404 status error |
||
71 | */ |
||
72 | 4 | View Code Duplication | public function containerExists(string $name): bool |
84 | } |
||
85 |
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: