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 |
||
12 | View Code Duplication | class Graph extends BaseType |
|
|
|||
13 | { |
||
14 | /** @var array */ |
||
15 | protected $hidden = []; |
||
16 | |||
17 | public function __call(string $method, array $arguments) |
||
18 | { |
||
19 | if (is_callable([Schema::class, $method])) { |
||
20 | return $this->getOrCreate((new ReflectionClass(Schema::class))->getMethod($method)->getReturnType()); |
||
21 | } |
||
22 | |||
23 | throw new BadMethodCallException(sprintf('The method "%" does not exist on class "%s".', $method, get_class($this))); |
||
24 | } |
||
25 | |||
26 | public function add(Type $schema) |
||
35 | |||
36 | public function has(string $type): bool |
||
37 | { |
||
38 | return $this->offsetExists($type); |
||
39 | } |
||
40 | |||
41 | public function set(Type $schema) |
||
42 | { |
||
43 | return $this->setProperty(get_class($schema), $schema); |
||
44 | } |
||
45 | |||
46 | public function get(string $type): Type |
||
54 | |||
55 | public function getOrCreate(string $type): Type |
||
65 | |||
66 | public function hide(string $type) |
||
67 | { |
||
68 | $this->hidden[$type] = true; |
||
69 | |||
70 | return $this; |
||
71 | } |
||
72 | |||
73 | public function show(string $type) |
||
74 | { |
||
75 | $this->hidden[$type] = false; |
||
76 | |||
77 | return $this; |
||
78 | } |
||
79 | |||
80 | public function toArray(): array |
||
94 | } |
||
95 |
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.