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 |
||
9 | class CreditCard |
||
10 | { |
||
11 | private $cardNumber; |
||
12 | private $expireDateMonth; |
||
13 | private $expireDateYear; |
||
14 | private $nameOnCard; |
||
15 | private $cardVerificationVal; |
||
16 | private $cardType; // check values of Zend\Validator\CreditCard::$cardName |
||
17 | |||
18 | protected static $validCardTypes = [ |
||
19 | 'All', |
||
20 | 'American_Express', |
||
21 | 'Unionpay', |
||
22 | 'Diners_Club', |
||
23 | 'Diners_Club_US', |
||
24 | 'Discover', |
||
25 | 'JCB', |
||
26 | 'Laser', |
||
27 | 'Maestro', |
||
28 | 'Mastercard', |
||
29 | 'Solo', |
||
30 | 'Visa' |
||
31 | ]; |
||
32 | |||
33 | public function __construct( |
||
49 | |||
50 | public function validate() |
||
59 | |||
60 | private function validateCardType() |
||
68 | |||
69 | private function validateCardNumber() |
||
78 | |||
79 | private function validatecardVerificationValue() |
||
80 | { |
||
81 | View Code Duplication | if (is_numeric($this->cardVerificationVal) |
|
|
|||
82 | && $this->cardType === CreditCardValidator::AMERICAN_EXPRESS |
||
83 | && strlen($this->cardVerificationVal) === 4 |
||
84 | ) { |
||
85 | return true; |
||
86 | } |
||
87 | View Code Duplication | if (is_numeric($this->cardVerificationVal) |
|
88 | && $this->cardType !== CreditCardValidator::AMERICAN_EXPRESS |
||
89 | && strlen($this->cardVerificationVal) === 3 |
||
90 | ) { |
||
91 | return true; |
||
92 | } |
||
93 | $message = sprintf('%s is not valid CVV.', $this->cardVerificationVal); |
||
94 | throw new InvalidArgumentException($message); |
||
95 | } |
||
96 | |||
97 | private function validateNameOnCard() |
||
105 | |||
106 | private function validateExpireDates() |
||
123 | } |
||
124 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.