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 Multiselect_Field extends Predefined_Options_Field { |
||
| 12 | |||
| 13 | /** |
||
| 14 | * The options limit. |
||
| 15 | * |
||
| 16 | * @var int |
||
| 17 | */ |
||
| 18 | protected $limit_options = 0; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * Default field value |
||
| 22 | * |
||
| 23 | * @var array |
||
| 24 | */ |
||
| 25 | protected $default_value = array(); |
||
| 26 | |||
| 27 | /** |
||
| 28 | * Create a field from a certain type with the specified label. |
||
| 29 | * |
||
| 30 | * @param string $type Field type |
||
| 31 | * @param string $name Field name |
||
| 32 | * @param string $label Field label |
||
| 33 | */ |
||
| 34 | public function __construct( $type, $name, $label ) { |
||
| 38 | |||
| 39 | /** |
||
| 40 | * Set the number of the options to be displayed at the initial field display. |
||
| 41 | * |
||
| 42 | * @param int $limit |
||
| 43 | */ |
||
| 44 | public function limit_options( $limit ) { |
||
| 48 | |||
| 49 | /** |
||
| 50 | * Load the field value from an input array based on its name |
||
| 51 | * |
||
| 52 | * @param array $input Array of field names and values. |
||
| 53 | * @return Field $this |
||
| 54 | */ |
||
| 55 | public function set_value_from_input( $input ) { |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Returns an array that holds the field data, suitable for JSON representation. |
||
| 70 | * |
||
| 71 | * @param bool $load Should the value be loaded from the database or use the value from the current instance. |
||
| 72 | * @return array |
||
| 73 | */ |
||
| 74 | View Code Duplication | public function to_json( $load ) { |
|
| 84 | /** |
||
| 85 | * Changes the options array structure. This is needed to keep the array items order when it is JSON encoded. |
||
| 86 | * Will also work with a callable that returns an array. |
||
| 87 | * |
||
| 88 | * @param array|callable $options |
||
| 89 | * @return array |
||
| 90 | */ |
||
| 91 | View Code Duplication | protected function parse_options( $options ) { |
|
| 107 | } |
||
| 108 |
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.