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 |
||
| 3 | class Navigation { |
||
| 4 | private $navigation; |
||
| 5 | private $last_ordre; |
||
| 6 | |||
| 7 | |||
| 8 | |||
| 9 | //-------------------------- BUILDER ----------------------------------------------------------------------------// |
||
| 10 | public function __construct() { |
||
| 31 | //-------------------------- END BUILDER ----------------------------------------------------------------------------// |
||
| 32 | |||
| 33 | |||
| 34 | |||
| 35 | //-------------------------- GETTER ----------------------------------------------------------------------------// |
||
| 36 | public function getNavigation() { |
||
| 39 | |||
| 40 | private function getLienNavigationPage($id_page) { |
||
| 58 | |||
| 59 | private function getSousMenu($id_page) { |
||
| 73 | |||
| 74 | private function getLienNavigationModule($id_module) { |
||
| 92 | //-------------------------- END GETTER ----------------------------------------------------------------------------// |
||
| 93 | |||
| 94 | |||
| 95 | |||
| 96 | //-------------------------- SETTER ----------------------------------------------------------------------------// |
||
| 97 | private function setNavigation($navigation) { |
||
| 100 | |||
| 101 | public function setTestAjoutLien($id, $value_id, $afficher) { |
||
| 108 | |||
| 109 | public function setSupprimerLien($id, $value_id) {echo("$id, $value_id"); |
||
| 114 | //-------------------------- END SETTER ----------------------------------------------------------------------------// |
||
| 115 | } |
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: