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 |
||
31 | View Code Duplication | class RaListingService |
|
|
|||
32 | { |
||
33 | /** |
||
34 | * @var LibraryRaListingService |
||
35 | */ |
||
36 | private $service; |
||
37 | |||
38 | /** |
||
39 | * @var ValidatorInterface |
||
40 | */ |
||
41 | private $validator; |
||
42 | |||
43 | /** |
||
44 | * @param LibraryRaListingService $service |
||
45 | * @param ValidatorInterface $validator |
||
46 | */ |
||
47 | public function __construct(LibraryRaListingService $service, ValidatorInterface $validator) |
||
52 | |||
53 | /** |
||
54 | * @param string $id |
||
55 | * @param string $institution |
||
56 | * @param string $actorInstitution |
||
57 | * @param string $actorId |
||
58 | * @return null|RaListing |
||
59 | */ |
||
60 | public function get($id, $institution, $actorId) |
||
61 | { |
||
62 | $data = $this->service->get($id, $institution, $actorId); |
||
63 | |||
64 | if ($data === null) { |
||
65 | return null; |
||
66 | } |
||
67 | |||
68 | $raListing = RaListing::fromData($data); |
||
69 | $message = sprintf("RaListing '%s' retrieved from the Middleware is invalid", $id); |
||
70 | $this->assertIsValid($raListing, $message); |
||
71 | |||
72 | return $raListing; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * @param RaListingSearchQuery $searchQuery |
||
77 | * @return RaListingCollection |
||
78 | */ |
||
79 | public function search(RaListingSearchQuery $searchQuery) |
||
98 | |||
99 | /** |
||
100 | * @param object $value |
||
101 | * @param null|string $message |
||
102 | */ |
||
103 | private function assertIsValid($value, $message = null) |
||
113 | } |
||
114 |
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.