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 |
||
| 7 | class CentreRecherche { |
||
| 8 | private $coef_centre; |
||
| 9 | |||
| 10 | |||
| 11 | //-------------------------- BUILDER ----------------------------------------------------------------------------// |
||
| 12 | public function __construct() { |
||
| 52 | |||
| 53 | /** |
||
| 54 | * @param $recherche |
||
| 55 | * @param $type |
||
| 56 | * @return int |
||
| 57 | * fonction qui va cehrcher le niveau de la recherche actuelle |
||
| 58 | * renvoi 0 si elle n'a pas été trouvée |
||
| 59 | */ |
||
| 60 | View Code Duplication | private function getNiveauRecherche($recherche, $type) { |
|
| 78 | //-------------------------- END BUILDER ----------------------------------------------------------------------------// |
||
| 79 | |||
| 80 | |||
| 81 | |||
| 82 | //-------------------------- GETTER ----------------------------------------------------------------------------// |
||
| 83 | /** |
||
| 84 | * @param $type |
||
| 85 | * @return array|int |
||
| 86 | * permet de renvoyer toutes es recherches déjà effectuées pour notre base en fonction |
||
| 87 | * d'un type donné |
||
| 88 | */ |
||
| 89 | public function getAllRechercheType($type) { |
||
| 107 | //-------------------------- END GETTER ----------------------------------------------------------------------------// |
||
| 108 | |||
| 109 | |||
| 110 | |||
| 111 | //-------------------------- SETTER ----------------------------------------------------------------------------// |
||
| 112 | //-------------------------- END SETTER ----------------------------------------------------------------------------// |
||
| 113 | |||
| 114 | } |
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArrayis initialized the first time when the foreach loop is entered. You can also see that the value of thebarkey is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.