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 |
||
14 | class Ratings |
||
15 | { |
||
16 | /** @var ApiClientInterface */ |
||
17 | private $client; |
||
18 | |||
19 | /** @var Video [] */ |
||
20 | private $videos = []; |
||
21 | |||
22 | /** @var int */ |
||
23 | private $vmId; |
||
24 | |||
25 | /** @var string */ |
||
26 | private $metadataFieldAverage; |
||
27 | |||
28 | /** @var string */ |
||
29 | private $metadataFieldCount; |
||
30 | |||
31 | public function __construct( |
||
42 | |||
43 | /** |
||
44 | * Increases the count of all ratings by one and calculates a new average rating value. |
||
45 | * |
||
46 | * @param string $videoId |
||
47 | * @param int $rating |
||
48 | */ |
||
49 | public function addRating($videoId, $rating) |
||
62 | |||
63 | /** |
||
64 | * Modifies the average rating value. Count of all ratings stays the same (will not be increased). |
||
65 | * The use case of this function is, when someone wants to change its rating (video was already rated by that person). |
||
66 | * |
||
67 | * @param string $videoId |
||
68 | * @param int $rating |
||
69 | * @param int $oldRating |
||
70 | */ |
||
71 | public function modifyRating($videoId, $rating, $oldRating) |
||
82 | |||
83 | /** |
||
84 | * Returns the average rating value from the custom meta data fields from a given video. |
||
85 | * |
||
86 | * @param string $videoId |
||
87 | * |
||
88 | * @return int |
||
89 | */ |
||
90 | View Code Duplication | private function getRatingAverage($videoId) |
|
98 | |||
99 | /** |
||
100 | * Returns the count of all ratings from the custom meta data fields from a given video. |
||
101 | * |
||
102 | * @param string $videoId |
||
103 | * |
||
104 | * @return int |
||
105 | */ |
||
106 | View Code Duplication | private function getRatingCount($videoId) |
|
114 | |||
115 | /** |
||
116 | * Stores the custom meta data fields with the api client. |
||
117 | * |
||
118 | * @param array $customMetaData |
||
119 | * @param string $videoId |
||
120 | */ |
||
121 | private function storeCustomMetaData($customMetaData, $videoId) |
||
129 | |||
130 | /** |
||
131 | * Fetches and returns video from api client and stores it locally. |
||
132 | * This way api client will be requested only once for every video. |
||
133 | * |
||
134 | * @param string $videoId |
||
135 | * |
||
136 | * @return Video |
||
137 | */ |
||
138 | private function getVideo($videoId) |
||
148 | } |
||
149 |
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.