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 |
||
10 | class MaterialField extends \samson\activerecord\MaterialField |
||
11 | { |
||
12 | /** Store entity name */ |
||
13 | const ENTITY = __CLASS__; |
||
14 | |||
15 | /** Entity field names constants for using in code */ |
||
16 | const F_PRIMARY = 'MaterialFieldID'; |
||
17 | const F_DELETION = 'Active'; |
||
18 | const F_LOCALE = 'locale'; |
||
19 | const F_VALUE = 'Value'; |
||
20 | const F_NUMERIC = 'numeric_value'; |
||
21 | const F_KEY = 'key_value'; |
||
22 | const F_MATERIALID = 'MaterialID'; |
||
23 | const F_FIELDID = 'FieldID'; |
||
24 | |||
25 | /** |
||
26 | * Find additional field value records by its material identifiers. |
||
27 | * |
||
28 | * @param QueryInterface $query Query object instance |
||
29 | * @param string $materialID Material identifier |
||
30 | * @param mixed $return Variable to return found database record |
||
31 | * @param string $locale Locale identifier |
||
32 | * @return bool|self[] Field instance or null if 3rd parameter not passed |
||
33 | */ |
||
34 | View Code Duplication | public static function byMaterialID( |
|
|
|||
35 | QueryInterface $query, |
||
36 | $materialID, |
||
37 | &$return = null, |
||
38 | $locale = DEFAULT_LOCALE |
||
39 | ) { |
||
40 | $return = $query->entity(get_called_class()) |
||
41 | ->where(Material::F_PRIMARY, $materialID) |
||
42 | ->where(Material::F_DELETION, true) |
||
43 | ->where(self::F_LOCALE, $locale) |
||
44 | ->exec(); |
||
45 | |||
46 | // If only one argument is passed - return null, otherwise bool |
||
47 | return func_num_args() > 2 ? sizeof($return) : $return; |
||
48 | } |
||
49 | |||
50 | /** |
||
51 | * Find additional field value database record by its material and field identifiers. |
||
52 | * This is generic method that should be used in nested classes to find its |
||
53 | * records by some its primary key value. |
||
54 | * |
||
55 | * @param QueryInterface $query Query object instance |
||
56 | * @param string $materialID Material identifier |
||
57 | * @param string $fieldID Additional field identifier |
||
58 | * @param mixed $return Variable to return found database record |
||
59 | * @param string $locale Locale identifier |
||
60 | * @return bool|null|self Field instance or null if 3rd parameter not passed |
||
61 | */ |
||
62 | View Code Duplication | public static function byFieldIDAndMaterialID( |
|
79 | } |
||
80 |
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.