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 |
||
8 | class Vote extends ActiveRecordModelExtender |
||
9 | { |
||
10 | |||
11 | /** |
||
12 | * @var string $tableName name of the database table. |
||
13 | */ |
||
14 | protected $tableName = "coffee_votes"; |
||
15 | |||
16 | /** |
||
17 | * Columns in the table. |
||
18 | * |
||
19 | * @var integer $id primary key auto incremented. |
||
20 | */ |
||
21 | public $id; |
||
22 | public $user; # question/answer/comment |
||
23 | public $parentId; # All posts have different ids |
||
24 | public $parentType; # post or comment |
||
25 | public $upVote; |
||
26 | public $downVote; |
||
27 | |||
28 | |||
29 | /** |
||
30 | * Return a vote |
||
31 | * @param string $sql |
||
32 | * @param array $params |
||
33 | * |
||
34 | * @return object |
||
35 | */ |
||
36 | 11 | public function getVote($sql, $params) |
|
50 | |||
51 | /** |
||
52 | * Checks if vote already exists, then either create new or update |
||
53 | * @param array $params |
||
54 | * |
||
55 | * @return bool |
||
56 | */ |
||
57 | 2 | public function saveVote($user, $parentId, $parentType, $voteType = "like") |
|
85 | |||
86 | /** |
||
87 | * Control if user has already liked or not |
||
88 | * @param string $user |
||
89 | * @param array $params |
||
90 | * |
||
91 | * @return bool |
||
92 | */ |
||
93 | 1 | View Code Duplication | public function like($user, $parentId, $parentType) |
107 | |||
108 | /** |
||
109 | * Control if user has already liked or not |
||
110 | * @param string $user |
||
111 | * @param array $params |
||
112 | * |
||
113 | * @return bool |
||
114 | */ |
||
115 | 1 | View Code Duplication | public function dislike($user, $parentId, $parentType) |
129 | } |
||
130 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: