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 |
||
| 27 | class Buttonbox extends AbstractTemplate |
||
| 28 | { |
||
| 29 | /** |
||
| 30 | * @var array |
||
| 31 | */ |
||
| 32 | private $items = array(); |
||
| 33 | |||
| 34 | /** |
||
| 35 | * @var string |
||
| 36 | */ |
||
| 37 | private $delimiter = " "; |
||
| 38 | |||
| 39 | /** |
||
| 40 | * @var string |
||
| 41 | */ |
||
| 42 | private $position = "right"; |
||
| 43 | |||
| 44 | /** |
||
| 45 | * @var string |
||
| 46 | */ |
||
| 47 | private $path = ''; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * init |
||
| 51 | * |
||
| 52 | * @return void |
||
| 53 | */ |
||
| 54 | protected function init() |
||
| 57 | |||
| 58 | /** |
||
| 59 | * set position - alignment position |
||
| 60 | * |
||
| 61 | * @param string $position left, right, center |
||
| 62 | * |
||
| 63 | * @return Buttonbox |
||
| 64 | */ |
||
| 65 | public function setPosition($position) |
||
| 70 | |||
| 71 | /** |
||
| 72 | * set path - path to image files. Do not set if icons are |
||
| 73 | * specified with absolute URLs |
||
| 74 | * |
||
| 75 | * @param string $path URL path to image files |
||
| 76 | * |
||
| 77 | * @return Buttonbox |
||
| 78 | */ |
||
| 79 | public function setImagePath($path) |
||
| 84 | |||
| 85 | /** |
||
| 86 | * setDelimiter |
||
| 87 | * |
||
| 88 | * @param string $delimiter delimiter put between buttons |
||
| 89 | * |
||
| 90 | * @return Buttonbox |
||
| 91 | */ |
||
| 92 | public function setDelimiter($delimiter) |
||
| 97 | |||
| 98 | /** |
||
| 99 | * addItem to button box |
||
| 100 | * |
||
| 101 | * @param string $title title string for button |
||
| 102 | * @param string $link link for button |
||
| 103 | * @param string $icon icon for button |
||
| 104 | * @param string $extra extra |
||
| 105 | * |
||
| 106 | * @return Buttonbox |
||
| 107 | */ |
||
| 108 | View Code Duplication | public function addItem($title, $link, $icon, $extra = '') |
|
| 117 | |||
| 118 | /** |
||
| 119 | * render the buttonbox |
||
| 120 | * |
||
| 121 | * @return void |
||
| 122 | */ |
||
| 123 | protected function render() |
||
| 150 | } |
||
| 151 |
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.