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 |
||
| 13 | class Compatibility { |
||
| 14 | |||
| 15 | /** |
||
| 16 | * Supported features are stored here on per-plugin basis. |
||
| 17 | * |
||
| 18 | * @var array |
||
| 19 | */ |
||
| 20 | private static $features = array(); |
||
| 21 | |||
| 22 | /** |
||
| 23 | * Mark a feature as supported by the plugin. |
||
| 24 | * |
||
| 25 | * @param string $plugin The plugin slug. |
||
| 26 | * @param string $feature The feature label. |
||
| 27 | */ |
||
| 28 | public static function add_feature( $plugin, $feature ) { |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Check if all the plugins support a feature. |
||
| 40 | * |
||
| 41 | * @param string $feature The feature label. |
||
| 42 | * |
||
| 43 | * @return bool True if the feature is supported, false otherwise. |
||
| 44 | */ |
||
| 45 | public static function can_use( $feature ) { |
||
| 54 | |||
| 55 | /** |
||
| 56 | * Let the package know that the plugin exists and needs to be checked for compatibility. |
||
| 57 | * |
||
| 58 | * @param string $plugin The plugin slug. |
||
| 59 | */ |
||
| 60 | public static function add_plugin( $plugin ) { |
||
| 65 | |||
| 66 | } |
||
| 67 |
Let’s assume you have a class which uses late-static binding:
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClassto useselfinstead: