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 |
||
14 | class BaseNode |
||
15 | { |
||
16 | /** |
||
17 | * @var ConstraintInterface[] |
||
18 | */ |
||
19 | protected $constraints = []; |
||
20 | |||
21 | /** |
||
22 | * @var TransformerInterface |
||
23 | */ |
||
24 | protected $transformer; |
||
25 | |||
26 | /** |
||
27 | * @var InstantiatorInterface |
||
28 | */ |
||
29 | protected $instantiator; |
||
30 | |||
31 | /** |
||
32 | * @var string |
||
33 | */ |
||
34 | protected $type = 'array'; |
||
35 | |||
36 | /** |
||
37 | * @var bool |
||
38 | */ |
||
39 | protected $required = true; |
||
40 | |||
41 | /** |
||
42 | * @var mixed |
||
43 | */ |
||
44 | protected $default; |
||
45 | |||
46 | /** |
||
47 | * @var BaseNode[] |
||
48 | */ |
||
49 | protected $children = []; |
||
50 | |||
51 | /** |
||
52 | * @var TypeHandler |
||
53 | */ |
||
54 | protected $typeHandler; |
||
55 | |||
56 | public function setConstraints(array $constraints) |
||
60 | |||
61 | public function addConstraint(ConstraintInterface $constraint) |
||
65 | |||
66 | public function setTransformer(TransformerInterface $transformer) |
||
70 | |||
71 | public function setInstantiator(InstantiatorInterface $instantiator) |
||
75 | |||
76 | public function setTypeHandler(TypeHandler $typeHandler) |
||
80 | |||
81 | public function setType(string $type) |
||
85 | |||
86 | public function setRequired(bool $required) |
||
90 | |||
91 | public function setDefault($default) |
||
95 | |||
96 | public function getDefault() |
||
100 | |||
101 | public function hasDefault(): bool |
||
105 | |||
106 | public function add(string $key, string $type, array $options = []): BaseNode |
||
143 | |||
144 | public function remove(string $key) |
||
148 | |||
149 | /** |
||
150 | * @return BaseNode[] |
||
151 | */ |
||
152 | public function getChildren(): array |
||
156 | |||
157 | public function hasChildren(): bool |
||
161 | |||
162 | public function isRequired(): bool |
||
170 | |||
171 | public function getValue(string $field, $value) |
||
181 | |||
182 | public function walk($input) |
||
208 | |||
209 | protected function checkConstraints(string $field, $value) |
||
217 | } |
||
218 |
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.