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 |
||
12 | class Comment_Meta_Container extends Container { |
||
13 | protected $comment_id; |
||
14 | |||
15 | /** |
||
16 | * Create a new comment meta container |
||
17 | * |
||
18 | * @param string $title Unique title of the container |
||
19 | **/ |
||
20 | public function __construct( $title ) { |
||
27 | |||
28 | /** |
||
29 | * Assign DataStore instance for use by the container fields |
||
30 | * |
||
31 | * @param object $store |
||
32 | **/ |
||
33 | public function set_datastore( Meta_Datastore $store ) { |
||
36 | |||
37 | /** |
||
38 | * Perform instance initialization after calling setup() |
||
39 | **/ |
||
40 | public function init() { |
||
48 | |||
49 | /** |
||
50 | * Checks whether the current request is valid |
||
51 | * |
||
52 | * @return bool |
||
53 | **/ |
||
54 | View Code Duplication | public function is_valid_save() { |
|
61 | |||
62 | /** |
||
63 | * Add meta box to the comment |
||
64 | **/ |
||
65 | public function attach() { |
||
75 | |||
76 | /** |
||
77 | * Revert the result of attach() |
||
78 | **/ |
||
79 | View Code Duplication | public function detach() { |
|
90 | |||
91 | /** |
||
92 | * Output the container markup |
||
93 | **/ |
||
94 | public function render() { |
||
97 | |||
98 | /** |
||
99 | * Set the comment ID the container will operate with. |
||
100 | * |
||
101 | * @param int $comment_id |
||
102 | **/ |
||
103 | public function set_comment_id( $comment_id ) { |
||
107 | |||
108 | /** |
||
109 | * Perform save operation after successful is_valid_save() check. |
||
110 | * The call is propagated to all fields in the container. |
||
111 | * |
||
112 | * @param int $comment_id ID of the comment against which save() is ran |
||
113 | **/ |
||
114 | public function save( $comment_id ) { |
||
126 | |||
127 | /** |
||
128 | * Perform checks whether there is a field registered with the name $name. |
||
129 | * If not, the field name is recorded. |
||
130 | * |
||
131 | * @param string $name |
||
132 | **/ |
||
133 | public function verify_unique_field_name( $name ) { |
||
144 | |||
145 | /** |
||
146 | * Remove field name $name from the list of unique field names |
||
147 | * |
||
148 | * @param string $name |
||
149 | **/ |
||
150 | public function drop_unique_field_name( $name ) { |
||
156 | |||
157 | } |
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.