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 |
||
21 | abstract class AbstractRenderer |
||
22 | { |
||
23 | |||
24 | /** |
||
25 | * @var ElementInterface |
||
26 | */ |
||
27 | protected $element; |
||
28 | |||
29 | /** |
||
30 | * @var EngineInterface |
||
31 | */ |
||
32 | protected $engine; |
||
33 | |||
34 | /** |
||
35 | * Creates an abstract render with element dependency. |
||
36 | * |
||
37 | * @param ElementInterface|null $element |
||
38 | */ |
||
39 | 20 | public function __construct(ElementInterface $element = null) |
|
43 | |||
44 | /** |
||
45 | * Returns current element |
||
46 | * |
||
47 | * @return ElementInterface |
||
48 | */ |
||
49 | 20 | public function getElement() |
|
53 | |||
54 | /** |
||
55 | * Sets HTML element to render |
||
56 | * |
||
57 | * @param ElementInterface $element |
||
58 | * |
||
59 | * @return $this|self|AbstractRenderer |
||
60 | */ |
||
61 | 20 | public function setElement(ElementInterface $element) |
|
66 | |||
67 | /** |
||
68 | * Returns the current template engine |
||
69 | * |
||
70 | * If no template is provided a new one is created with default settings. |
||
71 | * |
||
72 | * @return EngineInterface |
||
73 | */ |
||
74 | 20 | public function getEngine() |
|
81 | |||
82 | /** |
||
83 | * Sets current template engine |
||
84 | * |
||
85 | * @param EngineInterface $engine |
||
86 | * |
||
87 | * @return $this|self|AbstractRenderer |
||
88 | */ |
||
89 | 20 | public function setEngine($engine) |
|
94 | |||
95 | /** |
||
96 | * Returns the elements's attributes as a string |
||
97 | * |
||
98 | * @return string |
||
99 | */ |
||
100 | 18 | View Code Duplication | public function getAttributes() |
113 | |||
114 | /** |
||
115 | * Render the HTML element in the provided context |
||
116 | * |
||
117 | * @param array $context |
||
118 | * |
||
119 | * @return string The HTML string output |
||
120 | */ |
||
121 | 20 | public function render($context = []) |
|
126 | } |
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.