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 |
||
| 23 | class Tag |
||
| 24 | { |
||
| 25 | protected $_name; |
||
| 26 | protected $_date; |
||
| 27 | protected $_notes = []; |
||
| 28 | |||
| 29 | 3 | public function __construct($tag, $date = null, array $notes = []) |
|
| 39 | |||
| 40 | public function set(Tag $tag) |
||
| 46 | |||
| 47 | 3 | public function setName($value) |
|
| 53 | |||
| 54 | 3 | public function getName() |
|
| 58 | |||
| 59 | /** |
||
| 60 | * Appends note along with commmits. |
||
| 61 | * @param Note $note |
||
| 62 | */ |
||
| 63 | 1 | public function addNote(Note $note) |
|
| 67 | |||
| 68 | /** |
||
| 69 | * Appends notes along with commits. |
||
| 70 | * @param Note[] $notes array of notes |
||
| 71 | * @param boolean $prepend default is append |
||
| 72 | */ |
||
| 73 | 3 | public function addNotes(array $notes, $prepend = false) |
|
| 84 | |||
| 85 | /** |
||
| 86 | * Set notes. |
||
| 87 | * @param Note[] $notes array of notes |
||
| 88 | */ |
||
| 89 | 3 | public function setNotes(array $notes) |
|
| 93 | |||
| 94 | /** |
||
| 95 | * Sets date. |
||
| 96 | * Checks if it is date and later then current. |
||
| 97 | * @param mixed $value date |
||
| 98 | * @return Tag this |
||
| 99 | */ |
||
| 100 | 3 | View Code Duplication | public function setDate($value) |
| 109 | |||
| 110 | /** |
||
| 111 | * Unsets date. |
||
| 112 | */ |
||
| 113 | 2 | public function unsetDate() |
|
| 119 | |||
| 120 | 3 | public function getDate() |
|
| 124 | |||
| 125 | 3 | public function findNote($note) |
|
| 133 | |||
| 134 | 3 | public function getNotes() |
|
| 138 | |||
| 139 | /** |
||
| 140 | * Finds date of the tag which is the date of the latest commit. |
||
| 141 | * @return string|null date or null if no commits |
||
| 142 | */ |
||
| 143 | public function findDate() |
||
| 157 | } |
||
| 158 |
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.