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 |
||
25 | class Queue implements Countable { |
||
26 | private $head; |
||
27 | private $tail; |
||
28 | private $size; |
||
29 | private $maxSize; |
||
30 | |||
31 | View Code Duplication | public function __construct($maxSize = 0) { |
|
40 | |||
41 | /** |
||
42 | * Returns the queue size. |
||
43 | * |
||
44 | * @return int the length |
||
45 | */ |
||
46 | public function size() : int { |
||
49 | |||
50 | /** |
||
51 | * Checks if the queue is empty. |
||
52 | * |
||
53 | * @return bool true if is empty, else false. |
||
54 | */ |
||
55 | public function empty() : bool { |
||
58 | |||
59 | /** |
||
60 | * Add a new node at the end of the queue. |
||
61 | * |
||
62 | * @param mixed $data the data to store. |
||
63 | * @throws DataStructures\Exceptions\FullException if the queue is full. |
||
64 | */ |
||
65 | public function enqueue($data) { |
||
66 | if($this->isFull()) { |
||
67 | throw new FullException(); |
||
68 | } |
||
69 | |||
70 | $newNode = new Node($data); |
||
71 | if($this->head === null) { |
||
72 | $this->head = &$newNode; |
||
73 | $this->tail = &$this->head; |
||
74 | $newNode->next = &$this->tail; |
||
75 | } else { |
||
76 | $this->tail->next = &$newNode; |
||
77 | $newNode->next = &$this->head; |
||
78 | $this->tail = &$newNode; |
||
79 | } |
||
80 | $this->size++; |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * Removes the first node in the queue. |
||
85 | * |
||
86 | * @return mixed |
||
87 | */ |
||
88 | public function dequeue() { |
||
109 | |||
110 | /** |
||
111 | * Gets the element at the front of the queue without removing it. |
||
112 | * |
||
113 | * @return mixed |
||
114 | */ |
||
115 | public function peek() { |
||
118 | |||
119 | /** |
||
120 | * Returns true if is full the queue and false if there is |
||
121 | * space available. |
||
122 | * |
||
123 | * @return bool |
||
124 | */ |
||
125 | View Code Duplication | public function isFull() { |
|
132 | |||
133 | /** |
||
134 | * Binds to count() method. This is equal to make $this->queue->size(). |
||
135 | * |
||
136 | * @return integer the queue size. 0 if it is empty. |
||
137 | */ |
||
138 | public function count() { |
||
141 | } |
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.