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 |
||
21 | View Code Duplication | class BlogCategory extends DataObject implements CategorisationObject |
|
|
|||
22 | { |
||
23 | use BlogObject; |
||
24 | |||
25 | /** |
||
26 | * Use an exception code so that attempted writes can continue on |
||
27 | * duplicate errors. |
||
28 | * |
||
29 | * @const string |
||
30 | * This must be a string because ValidationException has decided we can't use int |
||
31 | */ |
||
32 | const DUPLICATE_EXCEPTION = 'DUPLICATE'; |
||
33 | |||
34 | /** |
||
35 | * {@inheritDoc} |
||
36 | * @var string |
||
37 | */ |
||
38 | private static $table_name = 'BlogCategory'; |
||
39 | |||
40 | /** |
||
41 | * @var array |
||
42 | */ |
||
43 | private static $db = array( |
||
44 | 'Title' => 'Varchar(255)', |
||
45 | 'URLSegment' => 'Varchar(255)' |
||
46 | ); |
||
47 | |||
48 | /** |
||
49 | * @var array |
||
50 | */ |
||
51 | private static $has_one = array( |
||
52 | 'Blog' => 'SilverStripe\\Blog\\Model\\Blog', |
||
53 | ); |
||
54 | |||
55 | /** |
||
56 | * @var array |
||
57 | */ |
||
58 | private static $belongs_many_many = array( |
||
59 | 'BlogPosts' => 'SilverStripe\\Blog\\Model\\BlogPost', |
||
60 | ); |
||
61 | |||
62 | /** |
||
63 | * {@inheritdoc} |
||
64 | */ |
||
65 | protected function getListUrlSegment() |
||
69 | |||
70 | /** |
||
71 | * {@inheritdoc} |
||
72 | */ |
||
73 | protected function getDuplicateError() |
||
77 | } |
||
78 |
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.