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 | * Display all the staff. |
||
| 39 | * |
||
| 40 | * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View |
||
| 41 | */ |
||
| 42 | public function index() |
||
| 47 | |||
| 48 | /** |
||
| 49 | * Set the user available. |
||
| 50 | * |
||
| 51 | * @return \Illuminate\Http\RedirectResponse |
||
| 52 | */ |
||
| 53 | View Code Duplication | public function setAvailable() |
|
| 61 | |||
| 62 | /** |
||
| 63 | * Set the user unavailable. |
||
| 64 | * |
||
| 65 | * @return \Illuminate\Http\RedirectResponse |
||
| 66 | */ |
||
| 67 | View Code Duplication | public function setUnavailable() |
|
| 75 | |||
| 76 | /** |
||
| 77 | * Display the profile. |
||
| 78 | * |
||
| 79 | * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View |
||
| 80 | */ |
||
| 81 | public function profile() |
||
| 85 | |||
| 86 | /** |
||
| 87 | * Destroy or multiple staff members. |
||
| 88 | * |
||
| 89 | * @param int $id THe id off the staff member in the database. |
||
| 90 | * @return \Illuminate\Http\RedirectResponse |
||
| 91 | */ |
||
| 92 | public function destroy($id) |
||
| 102 | } |
||
| 103 |
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.