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 Version 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 Version, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
31 | final class Version extends Object implements IEquatable, IComparable |
||
32 | { |
||
33 | |||
34 | /** |
||
35 | * Crea una nueva instancia con los números principal, secundario, de |
||
36 | * compilación (opcional) y revisión (opcional). |
||
37 | * Para comprobar si la versión es válida, usar el método isValid. |
||
38 | * |
||
39 | * @param int $major Componente principal |
||
40 | * @param int $minor Componente secundario |
||
41 | * @param int|string|VersionComponent|null $build Componente de compilación |
||
42 | * @param int|string|VersionComponent|null $revision Componente de revisión |
||
43 | * |
||
44 | * @throws InvalidArgumentException |
||
45 | * */ |
||
46 | 32 | public function __construct($major, $minor, $build = null, $revision = null) |
|
47 | { |
||
48 | 32 | parent::__construct(); |
|
49 | 32 | unset($this->Major, $this->Minor, $this->Build, $this->Revision); |
|
50 | |||
51 | 32 | if (!is_integer($major)) { |
|
52 | $args = [ |
||
53 | 3 | 'class' => typeof($this)->Name, |
|
54 | 3 | 'name' => 'major', |
|
55 | 3 | 'pos' => 0, |
|
56 | 3 | 'expected' => typeof(0), |
|
57 | 3 | 'actual' => typeof($major), |
|
58 | ]; |
||
59 | |||
60 | 3 | $msg = msg('Invalid argument type.'); |
|
|
|||
61 | 3 | $msg .= msg( |
|
62 | 3 | ' "{name}" (position {pos}) must to be an instance of "{expected}"; "{actual}" given.', |
|
63 | 3 | $args |
|
64 | ); |
||
65 | 3 | $msg .= msg(' Convert value or use the "{class}::parse" (static) method.', $args); |
|
66 | |||
67 | 3 | throw new InvalidArgumentException($msg); |
|
68 | } |
||
69 | |||
70 | 29 | if (!is_integer($minor)) { |
|
71 | $args = [ |
||
72 | 2 | 'class' => typeof($this)->Name, |
|
73 | 2 | 'name' => 'minor', |
|
74 | 2 | 'pos' => 1, |
|
75 | 2 | 'expected' => typeof(0), |
|
76 | 2 | 'actual' => typeof($minor), |
|
77 | ]; |
||
78 | |||
79 | 2 | $msg = msg('Invalid argument type.'); |
|
80 | 2 | $msg .= msg( |
|
81 | 2 | ' "{name}" (position {pos}) must to be an instance of "{expected}"; "{actual}" given.', |
|
82 | 2 | $args |
|
83 | ); |
||
84 | 2 | $msg .= msg(' Convert value or use the "{class}::parse" (static) method.', $args); |
|
85 | |||
86 | 2 | throw new InvalidArgumentException($msg); |
|
87 | } |
||
88 | |||
89 | 27 | View Code Duplication | if ($major < 0) { |
90 | $args = [ |
||
91 | 1 | 'name' => 'major', |
|
92 | 1 | 'pos' => 0, |
|
93 | 1 | 'actual' => $major, |
|
94 | ]; |
||
95 | |||
96 | 1 | $msg = msg('Invalid argument value.'); |
|
97 | 1 | $msg .= msg( |
|
98 | 1 | ' "{name}" (position {pos}) must to be a positive number; "{actual}" given.', |
|
99 | 1 | $args |
|
100 | ); |
||
101 | |||
102 | 1 | throw new InvalidArgumentException($msg); |
|
103 | } |
||
104 | |||
105 | 26 | View Code Duplication | if ($minor < 0) { |
106 | $args = [ |
||
107 | 1 | 'name' => 'minor', |
|
108 | 1 | 'pos' => 1, |
|
109 | 1 | 'actual' => $minor, |
|
110 | ]; |
||
111 | |||
112 | 1 | $msg = msg('Invalid argument value.'); |
|
113 | 1 | $msg .= msg( |
|
114 | 1 | ' "{name}" (position {pos}) must to be a positive number; "{actual}" given.', |
|
115 | 1 | $args |
|
116 | ); |
||
117 | |||
118 | 1 | throw new InvalidArgumentException($msg); |
|
119 | } |
||
120 | |||
121 | 25 | $this->major = $major; |
|
122 | 25 | $this->minor = $minor; |
|
123 | 25 | $this->build = VersionComponent::Parse($build); |
|
124 | 24 | $this->revision = VersionComponent::Parse($revision); |
|
125 | 22 | } |
|
126 | |||
127 | /** |
||
128 | * Convierte una cadena a su representación del tipo Version. |
||
129 | * |
||
130 | * @param Version|string|int|float|array $value Objeto a convertir. |
||
131 | * |
||
132 | * @return Version Objeto convertido desde $value. |
||
133 | * */ |
||
134 | 11 | public static function parse($value) |
|
135 | { |
||
136 | 11 | if ($value instanceof Version) { |
|
137 | return $value; |
||
138 | } |
||
139 | |||
140 | 11 | $version = []; |
|
141 | |||
142 | // Try to convert into an array |
||
143 | 11 | if (is_integer($value)) { |
|
144 | // Integer for major value |
||
145 | $version = [$value, 0]; |
||
146 | 11 | } elseif (is_float($value)) { |
|
147 | // Integer part as major, and decimal part as minor |
||
148 | $version = sprintf("%F", $value); |
||
149 | $version = explode('.', $version); |
||
150 | 11 | } elseif (is_array($value)) { |
|
151 | // Implode first 4 places for major, minor, build and revision respectivally. |
||
152 | 5 | $version = array_slice($value, 0, 4); |
|
153 | 6 | } elseif (is_string($value)) { |
|
154 | 6 | $version = explode('.', $value); |
|
155 | } else { |
||
156 | $msg = msg('Unable to parse. Argument passed has an invalid type: "{0}".', typeof($value)); |
||
157 | throw new InvalidArgumentException($msg); |
||
158 | } |
||
159 | |||
160 | // $value ya debería ser un array. |
||
161 | 11 | $c = count($version); |
|
162 | |||
163 | 11 | if ($c > 4 || $c < 2) { |
|
164 | 4 | $msg = msg('Unable to parse. Argument passed has an invalid format: "{0}".', $value); |
|
165 | //var_dump($version); |
||
166 | 4 | throw new InvalidArgumentException($msg); |
|
167 | } |
||
168 | |||
169 | |||
170 | 8 | $major = (int) $version[0]; |
|
171 | 8 | $minor = (int) $version[1]; |
|
172 | 8 | $build = null; |
|
173 | 8 | $revision = null; |
|
174 | |||
175 | 8 | if (count($version) >= 3) { |
|
176 | 6 | $build = VersionComponent::Parse($version[2]); |
|
177 | |||
178 | 6 | if (count($version) == 4) { |
|
179 | 1 | $revision = VersionComponent::Parse($version[3]); |
|
180 | } |
||
181 | } |
||
182 | |||
183 | 8 | return new Version($major, $minor, $build, $revision); |
|
184 | } |
||
185 | |||
186 | /** |
||
187 | * Obtiene el valor del componente principal del número de versión del |
||
188 | * objeto actual. |
||
189 | * Esta propiedad es de sólo lectura. |
||
190 | * |
||
191 | * @var int Componente principal del número de versión. |
||
192 | * */ |
||
193 | public $Major; |
||
194 | private $major; |
||
195 | |||
196 | /** |
||
197 | * Getter for Major property. |
||
198 | * |
||
199 | * @return int |
||
200 | * @see Version::$major |
||
201 | */ |
||
202 | 56 | public function getMajor() |
|
206 | |||
207 | |||
208 | /** |
||
209 | * Obtiene el valor del componente secundario del número de versión del |
||
210 | * objeto actual. |
||
211 | * Esta propiedad es de sólo lectura. |
||
212 | * |
||
213 | * @var int Componente secundario del número de versión. |
||
214 | * */ |
||
215 | public $Minor; |
||
216 | private $minor; |
||
217 | |||
218 | /** |
||
219 | * Getter for minor property. |
||
220 | * |
||
221 | * @return int |
||
222 | * @see Version::$minor |
||
223 | */ |
||
224 | 35 | public function getMinor() |
|
228 | |||
229 | /** |
||
230 | * Obtiene el valor del componente de compilación del número de versión |
||
231 | * del objeto actual. |
||
232 | * Esta propiedad es de sólo lectura. |
||
233 | * |
||
234 | * @var VersionComponent Componente de compilación del número de versión. |
||
235 | * */ |
||
236 | public $Build; |
||
237 | private $build; |
||
238 | |||
239 | /** |
||
240 | * Getter for Build property. |
||
241 | * |
||
242 | * @return VersionComponent |
||
243 | * @see Version::$build |
||
244 | */ |
||
245 | 47 | public function getBuild() |
|
249 | |||
250 | /** |
||
251 | * Obtiene el valor del componente de revisión del número de versión del |
||
252 | * objeto actual. |
||
253 | * Esta propiedad es de sólo lectura. |
||
254 | * |
||
255 | * @var VersionComponent Componente de revisión del número de versión. |
||
256 | * */ |
||
257 | public $Revision; |
||
258 | private $revision; |
||
259 | |||
260 | /** |
||
261 | * Getter for Revision property. |
||
262 | * |
||
263 | * @return VersionComponent |
||
264 | * @see Version::$revision |
||
265 | */ |
||
266 | 42 | public function getRevision() |
|
270 | |||
271 | |||
272 | /** |
||
273 | * Convierte la instancia actual en su representación en cadena. |
||
274 | * Por defecto, si no están definidos los componentes de compilación y |
||
275 | * revisión, no se incluyen en la salida. |
||
276 | * Use el método isValid si quiere determinar si la versión es válida |
||
277 | * antes de devolver esta cadena. |
||
278 | * |
||
279 | * @return string Representación de la versión en forma de cadena: |
||
280 | * 'major.minor[.build[.revision]]' |
||
281 | * @see VersionComponent::isNull() |
||
282 | * @see Version::isValid() |
||
283 | * */ |
||
284 | 16 | public function toString() |
|
301 | |||
302 | /** |
||
303 | * Indica si la instancia actual es un número de versión válido. |
||
304 | * |
||
305 | * Se considera válido si: |
||
306 | * 1. Major o Minor es mayor a cero (0). No puede ser '0.0'. |
||
307 | * 2. Build y Revision son nulos (no están definidos). |
||
308 | * 3. Build está definido pero Revision no. |
||
309 | * 4. Ambos están definidos, pero no poseen la parte de la cadena. |
||
310 | * 5. Ambos están definidos, pero Build no posee la parte de cadena. |
||
311 | * 6. Build está definido y tiene la cadena, pero Revision no está definido. |
||
312 | * 7. Revision posee cadena, pero Build no. |
||
313 | * |
||
314 | * @return boolean Un valor que indica si la instancia actual es válida. |
||
315 | * */ |
||
316 | 16 | public function isValid() |
|
353 | |||
354 | /** |
||
355 | * Determina si el objeto $other especificado es igual a la instancia actual. |
||
356 | * |
||
357 | * @param Version $other El otro objeto a comparar. |
||
358 | * |
||
359 | * @return bool `true` si $other es igual esta instancia; caso contrario, |
||
360 | * `false`. |
||
361 | * */ |
||
362 | 32 | public function equals($other) |
|
376 | |||
377 | |||
378 | #region IComparable |
||
379 | |||
380 | /** |
||
381 | * Determina la posición relativa de esta instancia con respecto al objeto especificado. |
||
382 | * |
||
383 | * For types different than ``Version``: |
||
384 | * - ``integer`` and ``null`` are always < 0; |
||
385 | * - ``string`` and ``array`` are parsed and then evaluated (if is not parseable, always > 0); |
||
386 | * - other types are always > 0 |
||
387 | * |
||
388 | * @param Version|int|string|mixed $other |
||
389 | * The other object to compare with. |
||
390 | * |
||
391 | * @return integer|null |
||
392 | * Returns: |
||
393 | * - ``= 0`` if this instance is considered equivalent to $other; |
||
394 | * - ``> 0`` si esta instancia se considera mayor a $other; |
||
395 | * - ``< 0`` si esta instancia se considera menor a $other. |
||
396 | * - ``null`` if this instance can't be compared against $other . |
||
397 | * @see Object::compare() |
||
398 | * */ |
||
399 | 24 | public function compareTo($other) |
|
451 | |||
452 | #endregion |
||
453 | } |
||
454 |
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.