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 |
||
8 | class Table extends AbstractTableElement |
||
9 | { |
||
10 | /** |
||
11 | * @var TableRow[] |
||
12 | */ |
||
13 | protected $rows = array(); |
||
14 | |||
15 | /** |
||
16 | * @return TableRow[] |
||
17 | */ |
||
18 | 1 | public function getRows() |
|
19 | { |
||
20 | 1 | return $this->rows; |
|
21 | } |
||
22 | |||
23 | /** |
||
24 | * @param TableRow $row |
||
25 | */ |
||
26 | 1 | public function addRow(TableRow $row) |
|
27 | { |
||
28 | 1 | $this->rows[] = $row; |
|
29 | |||
30 | 1 | if (!$row->getTable()) { |
|
31 | 1 | $row->setTable($this); |
|
32 | } |
||
33 | 1 | } |
|
34 | |||
35 | /** |
||
36 | * @param TableRow $row |
||
37 | */ |
||
38 | public function removeRow(TableRow $row) |
||
39 | { |
||
40 | $key = array_search($row, $this->rows, true); |
||
41 | |||
42 | if ($key !== false) { |
||
43 | unset($this->rows[$key]); |
||
44 | if ($row->getTable()) { |
||
45 | $row->setTable(null); |
||
46 | } |
||
47 | } |
||
48 | } |
||
49 | |||
50 | /** |
||
51 | * @param int $index |
||
52 | * |
||
53 | * @return null|TableRow |
||
54 | */ |
||
55 | public function getRow($index) |
||
59 | |||
60 | /** |
||
61 | * @param TableRow[] $rows |
||
62 | * @param null|int $position |
||
63 | */ |
||
64 | View Code Duplication | public function insertRows($rows, $position = null) |
|
|
|||
65 | { |
||
66 | if ($position === null) { |
||
67 | $this->rows = array_merge($this->rows, $rows); |
||
68 | } else { |
||
69 | array_splice($this->rows, $position, 0, $rows); |
||
70 | } |
||
71 | } |
||
72 | |||
73 | /** |
||
74 | * @param TablePosition $position |
||
75 | * |
||
76 | * @return null|TableCell |
||
77 | */ |
||
78 | public function getCellByPosition(TablePosition $position) |
||
84 | |||
85 | /** |
||
86 | * @param TablePosition $position |
||
87 | * @param int $offset |
||
88 | * |
||
89 | * @return TablePosition|null |
||
90 | */ |
||
91 | public function getPositionBefore(TablePosition $position, $offset = 1) |
||
126 | |||
127 | /** |
||
128 | * @param TablePosition $position |
||
129 | * @param int $offset |
||
130 | * |
||
131 | * @return TablePosition|null |
||
132 | */ |
||
133 | public function getPositionAfter(TablePosition $position, $offset = 1) |
||
160 | } |
||
161 |
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.