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 |
||
47 | class SaleLimitOneValidator extends ItemValidator |
||
48 | { |
||
49 | /** |
||
50 | * @param ItemInterface $item |
||
51 | * @param PurchaseContext $context |
||
52 | * |
||
53 | * @throws InvalidItemException |
||
54 | */ |
||
55 | protected function validate(ItemInterface $item, PurchaseContext $context) |
||
56 | { |
||
57 | if (!$item->isProduct()) { |
||
58 | return; |
||
59 | } |
||
60 | |||
61 | $quantity = $item->getQuantity(); |
||
62 | if (1 < $quantity) { |
||
63 | $this->throwInvalidItemException('商品は1個しか購入できません。'); |
||
64 | } |
||
65 | } |
||
66 | |||
67 | protected function handle(ItemInterface $item, PurchaseContext $context) |
||
68 | { |
||
69 | $item->setQuantity(1); |
||
70 | } |
||
71 | } |
||
72 |