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 |
||
8 | abstract class AdvancedModelTransformer implements DataTransformerInterface |
||
9 | { |
||
10 | /** |
||
11 | * @var string[] |
||
12 | */ |
||
13 | protected $types; |
||
14 | |||
15 | /** |
||
16 | * @param string[] $types The types of the models |
||
17 | */ |
||
18 | 1 | public function __construct(array $types) |
|
26 | |||
27 | /** |
||
28 | * Transforms an object (model) to the form representation |
||
29 | * |
||
30 | * @param \Model|\Model[]|null $models |
||
31 | * @return array |
||
32 | */ |
||
33 | 1 | public function transform($models) |
|
61 | |||
62 | /** |
||
63 | * Get an invalid model of an acceptable type |
||
64 | * |
||
65 | * @param string|null $type The type of the model, or null to select one of |
||
66 | * the specified types |
||
67 | * @return \Model |
||
68 | */ |
||
69 | protected function invalidModel($type = null) |
||
79 | |||
80 | /** |
||
81 | * Get a model from its name |
||
82 | * @param string $name The name of the model |
||
83 | * @param string $type The type of the model in lower case |
||
84 | * @return \NamedModel|null The model or null if no name was specified |
||
85 | */ |
||
86 | 1 | protected function getModelFromName($name, $type) |
|
100 | |||
101 | /** |
||
102 | * Transform JSON data provided by javascript to a list of Models |
||
103 | * |
||
104 | * @param string $data The JSON provided to us by javascript, containing |
||
105 | * a list of Model IDs and types |
||
106 | * @param array $include An array of Models of each type that will be |
||
107 | * included in the final result |
||
108 | * @return bool|\Model[] A list of models, or false if the data was not |
||
109 | * provided by javascript as JSON |
||
110 | */ |
||
111 | 1 | protected function transformJSON(&$data, $include = array()) |
|
175 | } |
||
176 |
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.