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 |
||
12 | class UnicornService |
||
13 | { |
||
14 | /** @var EntityManager $em */ |
||
15 | private $em; |
||
16 | |||
17 | /** |
||
18 | * @param EntityManager $em |
||
19 | */ |
||
20 | public function __construct(EntityManager $em) |
||
24 | |||
25 | /** |
||
26 | * @param array $data |
||
27 | * @return Unicorn |
||
28 | */ |
||
29 | public function createFromArray(array $data): Unicorn |
||
35 | |||
36 | /** |
||
37 | * @param Unicorn $unicorn |
||
38 | * @param array $data |
||
39 | * @return Unicorn |
||
40 | */ |
||
41 | public function updateFromArray(Unicorn $unicorn, array $data): Unicorn |
||
57 | |||
58 | /** |
||
59 | * @param Unicorn $unicorn |
||
60 | * @return Unicorn |
||
61 | * @throws \Doctrine\ORM\ORMException |
||
62 | * @throws \Doctrine\ORM\OptimisticLockException |
||
63 | */ |
||
64 | public function saveUnicorn(Unicorn $unicorn): Unicorn |
||
68 | |||
69 | /** |
||
70 | * @param Unicorn $unicorn |
||
71 | * @throws \Doctrine\ORM\ORMException |
||
72 | * @throws \Doctrine\ORM\OptimisticLockException |
||
73 | */ |
||
74 | public function deleteUnicorn(Unicorn $unicorn): void |
||
78 | |||
79 | /** |
||
80 | * @return UnicornRepository |
||
81 | */ |
||
82 | public function getRepository(): UnicornRepository |
||
89 | } |
||
90 |
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.