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 |
||
13 | trait TimestampableTrait |
||
14 | { |
||
15 | /** |
||
16 | * Object creation date (set automatically on save) |
||
17 | * @var DateTimeInterface |
||
18 | */ |
||
19 | private $created; |
||
20 | |||
21 | /** |
||
22 | * Object last modified date (set automatically on save and update) |
||
23 | * @var DateTimeInterface |
||
24 | */ |
||
25 | private $lastModified; |
||
26 | |||
27 | /** |
||
28 | * @param \DateTimeInterface|string|null $created The object's creation timestamp. |
||
29 | * @throws InvalidArgumentException If the provided date/time is invalid. |
||
30 | * @return self |
||
31 | */ |
||
32 | View Code Duplication | public function setCreated($created) |
|
49 | |||
50 | /** |
||
51 | * @return DateTimeInterface|null |
||
52 | */ |
||
53 | public function getCreated() |
||
54 | { |
||
55 | return $this->created; |
||
56 | } |
||
57 | |||
58 | /** |
||
59 | * @param \DateTimeInterface|string|null $lastModified The object's last modified timestamp. |
||
60 | * @throws InvalidArgumentException If the provided date/time is invalid. |
||
61 | * @return self |
||
62 | */ |
||
63 | View Code Duplication | public function setLastModified($lastModified) |
|
80 | |||
81 | /** |
||
82 | * @return DateTimeInterface|null |
||
83 | */ |
||
84 | public function getLastModified() |
||
88 | } |
||
89 |
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.