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 |
||
32 | class WeakrefObjectStorage |
||
33 | { |
||
34 | /** |
||
35 | * An array of fetched object, accessible via table name and primary key. |
||
36 | * If the primary key is split on several columns, access is done by an array of columns, serialized. |
||
37 | * |
||
38 | * @var array<string, WeakMap<string, TDBMObject>> |
||
39 | */ |
||
40 | private $objects = array(); |
||
41 | |||
42 | /** |
||
43 | * Every 10000 set in the dataset, we perform a cleanup to ensure the WeakRef instances |
||
44 | * are removed if they are no more valid. |
||
45 | * This is to avoid having memory used by dangling WeakRef instances. |
||
46 | * |
||
47 | * @var int |
||
48 | */ |
||
49 | private $garbageCollectorCount = 0; |
||
50 | |||
51 | /** |
||
52 | * Sets an object in the storage. |
||
53 | * |
||
54 | * @param string $tableName |
||
55 | * @param string $id |
||
56 | * @param DbRow $dbRow |
||
57 | */ |
||
58 | public function set($tableName, $id, DbRow $dbRow) |
||
67 | |||
68 | /** |
||
69 | * Checks if an object is in the storage. |
||
70 | * |
||
71 | * @param string $tableName |
||
72 | * @param string $id |
||
73 | * |
||
74 | * @return bool |
||
75 | */ |
||
76 | public function has($tableName, $id) |
||
88 | |||
89 | /** |
||
90 | * Returns an object from the storage (or null if no object is set). |
||
91 | * |
||
92 | * @param string $tableName |
||
93 | * @param string $id |
||
94 | * |
||
95 | * @return DbRow |
||
96 | */ |
||
97 | public function get($tableName, $id) |
||
107 | |||
108 | /** |
||
109 | * Removes an object from the storage. |
||
110 | * |
||
111 | * @param string $tableName |
||
112 | * @param string $id |
||
113 | */ |
||
114 | public function remove($tableName, $id) |
||
118 | |||
119 | /** |
||
120 | * Applies the callback to all objects. |
||
121 | * |
||
122 | * @param callable $callback |
||
123 | */ |
||
124 | public function apply(callable $callback) |
||
136 | |||
137 | private function cleanupDanglingWeakRefs() |
||
147 | } |
||
148 |
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.