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 |
||
| 15 | class StaffController extends Controller |
||
| 16 | { |
||
| 17 | |||
| 18 | /** |
||
| 19 | * StaffController constructor. |
||
| 20 | */ |
||
| 21 | public function __construct() |
||
| 26 | |||
| 27 | /** |
||
| 28 | * Create new staff member. |
||
| 29 | * |
||
| 30 | * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View |
||
| 31 | */ |
||
| 32 | public function create() |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Store the new member in the database |
||
| 39 | * |
||
| 40 | * @TODO: Needs phpunit test. |
||
| 41 | * @return \Illuminate\Http\RedirectResponse |
||
| 42 | */ |
||
| 43 | public function store() |
||
| 47 | |||
| 48 | /** |
||
| 49 | * Edit view for a staff member. |
||
| 50 | * |
||
| 51 | * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View |
||
| 52 | */ |
||
| 53 | public function edit($id) |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Display all the staff. |
||
| 61 | * |
||
| 62 | * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View |
||
| 63 | */ |
||
| 64 | public function index() |
||
| 69 | |||
| 70 | /** |
||
| 71 | * Set the user available. |
||
| 72 | * |
||
| 73 | * @return \Illuminate\Http\RedirectResponse |
||
| 74 | */ |
||
| 75 | View Code Duplication | public function setAvailable() |
|
| 83 | |||
| 84 | /** |
||
| 85 | * Set the user unavailable. |
||
| 86 | * |
||
| 87 | * @return \Illuminate\Http\RedirectResponse |
||
| 88 | */ |
||
| 89 | View Code Duplication | public function setUnavailable() |
|
| 97 | |||
| 98 | /** |
||
| 99 | * Display the profile. |
||
| 100 | * |
||
| 101 | * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View |
||
| 102 | */ |
||
| 103 | public function profile() |
||
| 107 | |||
| 108 | /** |
||
| 109 | * Destroy or multiple staff members. |
||
| 110 | * |
||
| 111 | * @param int $id THe id off the staff member in the database. |
||
| 112 | * @return \Illuminate\Http\RedirectResponse |
||
| 113 | */ |
||
| 114 | public function destroy($id) |
||
| 124 | } |
||
| 125 |
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.