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) |
||
48 | { |
||
49 | $this->service = $service; |
||
50 | $this->validator = $validator; |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @param string $id |
||
55 | * @return null|RaListing |
||
56 | */ |
||
57 | public function get($id) |
||
71 | |||
72 | /** |
||
73 | * @param RaListingSearchQuery $searchQuery |
||
74 | * @return RaListingCollection |
||
75 | */ |
||
76 | public function search(RaListingSearchQuery $searchQuery) |
||
77 | { |
||
78 | $data = $this->service->search($searchQuery); |
||
79 | |||
80 | if ($data === null) { |
||
81 | throw new InvalidResponseException( |
||
82 | 'Received a "null" as data when searching for RaListings, is the library service set up correctly?' |
||
83 | ); |
||
84 | } |
||
85 | |||
86 | $registrationAuthorities = RaListingCollection::fromData($data); |
||
87 | |||
88 | $this->assertIsValid( |
||
89 | $registrationAuthorities, |
||
90 | 'One or more registration authority listings retrieved from the Middleware were invalid' |
||
91 | ); |
||
92 | |||
93 | return $registrationAuthorities; |
||
94 | } |
||
95 | |||
96 | /** |
||
97 | * @param object $value |
||
98 | * @param null|string $message |
||
99 | */ |
||
100 | private function assertIsValid($value, $message = null) |
||
110 | } |
||
111 |
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.