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 Calendar |
||
10 | { |
||
11 | private $today; // today as a reference (any day passed by the user) |
||
12 | private $padWithNull = false; // pad beginning or end of month with null instead of dates |
||
13 | private $startOfMonth; // first day of the current month |
||
14 | private $endOfMonth; // first day of the current month |
||
15 | private $currentMonth; // the calendar for the current month |
||
16 | |||
17 | public $startOfPrevMonth; |
||
18 | public $startOfNextMonth; |
||
19 | |||
20 | public function __construct(string $today) |
||
28 | |||
29 | public static function make(string $today): self |
||
33 | |||
34 | public function padWithNull(): self |
||
40 | |||
41 | public function grid(): array |
||
51 | |||
52 | // If first day of month > 1 (first week doesn't start on a Monday)... |
||
53 | // ...then pad the first week with remaining days from previous month |
||
54 | View Code Duplication | private function padStart(): void |
|
73 | |||
74 | // If last day of month < 7 (last week doesn't end on a Sunday)... |
||
75 | // ...then pad the last week with beginning days from next month |
||
76 | View Code Duplication | private function padEnd(): void |
|
95 | } |
||
96 |
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.