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 namespace Bedard\Shop\Api; |
||
| 8 | class Cart extends ApiController |
||
| 9 | { |
||
| 10 | /** |
||
| 11 | * Add an inventory to the cart. |
||
| 12 | * |
||
| 13 | * @param CartRepository $repository |
||
| 14 | */ |
||
| 15 | public function add(CartRepository $repository) |
||
| 28 | |||
| 29 | /** |
||
| 30 | * Determine if a cart exists or not. |
||
| 31 | * |
||
| 32 | * @param CartRepository $repository |
||
| 33 | * @return bool |
||
| 34 | */ |
||
| 35 | View Code Duplication | public function exists(CartRepository $repository) |
|
| 45 | |||
| 46 | /** |
||
| 47 | * Show the current cart. |
||
| 48 | * |
||
| 49 | * @param \Bedard\Shop\Repositories\CartRepository $repository |
||
| 50 | * @return \Bedard\Shop\Models\Cart |
||
| 51 | */ |
||
| 52 | View Code Duplication | public function index(CartRepository $repository) |
|
| 62 | |||
| 63 | /** |
||
| 64 | * Delete an item from the cart. |
||
| 65 | * |
||
| 66 | * @param CartRepository $repository |
||
| 67 | * @param int $inventoryId |
||
| 68 | * @return \Bedard\Shop\Models\Cart |
||
| 69 | */ |
||
| 70 | public function deleteItem(CartRepository $repository, $inventoryId) |
||
| 71 | { |
||
| 72 | try { |
||
| 73 | $repository->deleteItem($inventoryId); |
||
| 74 | |||
| 75 | return $repository->loadCart(); |
||
| 76 | } catch (Exception $e) { |
||
| 77 | Log::error($e->getMessage()); |
||
| 78 | |||
| 79 | abort(500, $e->getMessage()); |
||
| 80 | } |
||
| 81 | } |
||
| 82 | |||
| 83 | /** |
||
| 84 | * Create a new cart. |
||
| 85 | * |
||
| 86 | * @param \Bedard\Shop\Repositories\CartRepository $repository |
||
| 87 | * @return \Bedard\Shop\Models\Cart |
||
| 88 | */ |
||
| 89 | public function store(CartRepository $repository) |
||
| 100 | |||
| 101 | public function updateItem(CartRepository $repository) |
||
| 105 | } |
||
| 106 |
This check looks for
tryblocks that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.If there is nothing in the
trythen thecatchblock can never be executed either. Thus, thesetrystatements can be removed completely.