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 |
||
| 5 | class BlogAuthors extends Api |
||
| 6 | { |
||
| 7 | /** |
||
| 8 | * Create a new blog author. |
||
| 9 | * |
||
| 10 | * @param array $params Optional Parameters. |
||
| 11 | * @return \Fungku\HubSpot\Http\Response |
||
| 12 | */ |
||
| 13 | public function create($params = []) |
||
| 21 | |||
| 22 | /** |
||
| 23 | * Get all blog authors. |
||
| 24 | * |
||
| 25 | * @param array $params Optional parameters. |
||
| 26 | * @return \Fungku\HubSpot\Http\Response |
||
| 27 | */ |
||
| 28 | public function all($params = []) |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Search blog authors. |
||
| 39 | * |
||
| 40 | * @param string $query Search query |
||
| 41 | * @param array $params Optional parameters. |
||
| 42 | * @return \Fungku\HubSpot\Http\Response |
||
| 43 | */ |
||
| 44 | View Code Duplication | public function search($q = '', $params = []) |
|
| 54 | |||
| 55 | /** |
||
| 56 | * Update a blog author. |
||
| 57 | * |
||
| 58 | * @param int $id Unique identifier for a blog author. |
||
| 59 | * @param array $params Fields to update. |
||
| 60 | * @return \Fungku\HubSpot\Http\Response |
||
| 61 | */ |
||
| 62 | public function update($id, $params = []) |
||
| 70 | |||
| 71 | /** |
||
| 72 | * Delete a blog author. |
||
| 73 | * |
||
| 74 | * @param int $id Unique identifier for the blog author to delete. |
||
| 75 | * @return \Fungku\HubSpot\Http\Response |
||
| 76 | */ |
||
| 77 | public function delete($id) |
||
| 83 | |||
| 84 | /** |
||
| 85 | * Get a specific blog author. |
||
| 86 | * |
||
| 87 | * @param int $id Unique identifier for a blog author. |
||
| 88 | * @return \Fungku\HubSpot\Http\Response |
||
| 89 | */ |
||
| 90 | public function getById($id) |
||
| 96 | |||
| 97 | } |
||
| 98 |
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.