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:
Complex classes like ContestList often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ContestList, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class ContestList extends CModel |
||
20 | { |
||
21 | const LIFETIME = 172800; //2 days |
||
|
|||
22 | const BOARD_RANGE = 7; |
||
23 | |||
24 | private $id; |
||
25 | private $uid; |
||
26 | private $isValid; |
||
27 | private $collect; |
||
28 | private $prize; |
||
29 | private $maxScore; |
||
30 | private $list; |
||
31 | private $winners; |
||
32 | private $history; |
||
33 | private $collectTypes = [ |
||
34 | 'xp','xp_duel','xp_mission', |
||
35 | 'dollar','dollar_duel','dollar_mission' |
||
36 | ]; |
||
37 | |||
38 | public function attributeNames() |
||
42 | |||
43 | public function getId() |
||
47 | |||
48 | public function getCollect() |
||
52 | |||
53 | public function getPrize() |
||
57 | |||
58 | public function getDescriptionId() |
||
65 | |||
66 | public function getIsValid() |
||
74 | |||
75 | public function getIsActive() |
||
84 | |||
85 | public function getSecUntilEnd() |
||
90 | |||
91 | public function hasWinner() |
||
95 | |||
96 | public function getWinners() |
||
100 | |||
101 | public function getList() |
||
105 | |||
106 | public function getHistory() |
||
113 | |||
114 | public function getRankDescription() |
||
137 | |||
138 | public function getMaxScore() |
||
152 | |||
153 | public function getLastId() |
||
158 | |||
159 | public function getPrizePerWinner() |
||
167 | |||
168 | public function setId($id) |
||
172 | |||
173 | public function setUid($uid) |
||
177 | |||
178 | public function fetchDetails() |
||
185 | |||
186 | public function fetchList() |
||
209 | |||
210 | public function listBestPlayers() |
||
231 | |||
232 | public function canClaimPrize() |
||
252 | |||
253 | public function claimPrize() |
||
263 | |||
264 | public function seeContest() |
||
271 | } |
||
272 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.