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 |
||
19 | final class ArgumentFactoryAggregate implements ArgumentFactory |
||
20 | { |
||
21 | |||
22 | /** |
||
23 | * @var array<ArgumentFactory> |
||
24 | */ |
||
25 | private $innerArgumentFactories; |
||
26 | |||
27 | 9 | public function __construct(array $innerArgumentFactories) |
|
28 | { |
||
29 | 9 | Assert::null($this->innerArgumentFactories); |
|
30 | 9 | $this->innerArgumentFactories = array(); |
|
31 | |||
32 | 9 | foreach ($innerArgumentFactories as $innerArgumentFactory) { |
|
33 | /** @var ArgumentFactory $innerArgumentFactory */ |
||
34 | |||
35 | 9 | Assert::isInstanceOf($innerArgumentFactory, ArgumentFactory::class); |
|
36 | |||
37 | 9 | $this->innerArgumentFactories[] = $innerArgumentFactory; |
|
38 | } |
||
39 | 9 | } |
|
40 | |||
41 | 4 | public function understandsString(string $source): bool |
|
42 | { |
||
43 | /** @var bool $understandsString */ |
||
44 | 4 | $understandsString = false; |
|
45 | |||
46 | 4 | foreach ($this->innerArgumentFactories as $innerArgumentFactory) { |
|
47 | /** @var ArgumentFactory $innerArgumentFactory */ |
||
48 | |||
49 | 4 | $understandsString = $innerArgumentFactory->understandsString($source); |
|
50 | |||
51 | 4 | if ($understandsString) { |
|
52 | 4 | break; |
|
53 | } |
||
54 | } |
||
55 | |||
56 | 4 | return $understandsString; |
|
57 | } |
||
58 | |||
59 | 4 | public function understandsArray(array $source): bool |
|
60 | { |
||
61 | /** @var bool $understandsArray */ |
||
62 | 4 | $understandsArray = false; |
|
63 | |||
64 | 4 | foreach ($this->innerArgumentFactories as $innerArgumentFactory) { |
|
65 | /** @var ArgumentFactory $innerArgumentFactory */ |
||
66 | |||
67 | 4 | $understandsArray = $innerArgumentFactory->understandsArray($source); |
|
68 | |||
69 | 4 | if ($understandsArray) { |
|
70 | 4 | break; |
|
71 | } |
||
72 | } |
||
73 | |||
74 | 4 | return $understandsArray; |
|
75 | } |
||
76 | |||
77 | View Code Duplication | public function createArgumentFromString(string $source): Argument |
|
98 | |||
99 | View Code Duplication | public function createArgumentFromArray(array $source): Argument |
|
117 | |||
118 | } |
||
119 |
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.