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 |
||
11 | class Collection |
||
12 | { |
||
13 | /** |
||
14 | * @var string |
||
15 | */ |
||
16 | protected $name; |
||
17 | |||
18 | /** |
||
19 | * @var DocumentStore |
||
20 | */ |
||
21 | protected $store; |
||
22 | |||
23 | /** |
||
24 | * @var Database |
||
25 | */ |
||
26 | protected $database; |
||
27 | |||
28 | /** |
||
29 | * Construct a new collection. |
||
30 | * |
||
31 | * @param Database $database |
||
32 | * @param DocumentStore $store |
||
33 | * @param string $name |
||
34 | */ |
||
35 | public function __construct(Database $database, DocumentStore $store, $name) |
||
42 | |||
43 | /** |
||
44 | * Drop the collection. |
||
45 | * |
||
46 | * @return bool |
||
47 | */ |
||
48 | public function drop() |
||
52 | |||
53 | /** |
||
54 | * Remove all the documents from the collection. |
||
55 | * |
||
56 | * @return bool |
||
57 | */ |
||
58 | public function truncate() |
||
62 | |||
63 | /** |
||
64 | * Insert a new document. |
||
65 | * |
||
66 | * @param Identifiable $document |
||
67 | * |
||
68 | * @return bool |
||
69 | */ |
||
70 | public function insert(Identifiable $document) |
||
74 | |||
75 | /** |
||
76 | * Update existing documents. |
||
77 | * |
||
78 | * @param array $criteria |
||
79 | * @param Identifiable $updated |
||
80 | * @param bool $multiple |
||
81 | * |
||
82 | * @return int The count of the documents updated. |
||
83 | */ |
||
84 | View Code Duplication | public function update($criteria, Identifiable $updated, $multiple = false) |
|
93 | |||
94 | /** |
||
95 | * Remove documents from the collection. |
||
96 | * |
||
97 | * @param mixed $criteria |
||
98 | * @param bool $multiple |
||
99 | * |
||
100 | * @return int The count of the document deleted. |
||
101 | */ |
||
102 | View Code Duplication | public function remove($criteria, $multiple = false) |
|
114 | |||
115 | /** |
||
116 | * Find documents in the collection. |
||
117 | * |
||
118 | * @param array $criteria |
||
119 | * |
||
120 | * @return array The array of results. |
||
121 | */ |
||
122 | public function find($criteria) |
||
126 | |||
127 | protected function onMatch($criteria, $limit = null) |
||
136 | |||
137 | protected function newMatcher(ExpressionInterface $expression) |
||
141 | } |
||
142 |
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: