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 |
||
| 20 | class Notices { |
||
| 21 | |||
| 22 | /** |
||
| 23 | * Get notices. |
||
| 24 | * |
||
| 25 | * @since 3.0.0 |
||
| 26 | */ |
||
| 27 | public function __construct() { |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Process notices. |
||
| 34 | * |
||
| 35 | * @since 3.0.0 |
||
| 36 | */ |
||
| 37 | public function process_notices() { |
||
| 83 | |||
| 84 | /** |
||
| 85 | * Add notice. |
||
| 86 | * |
||
| 87 | * @TODO Improve notice dismissal with ajax. |
||
| 88 | * |
||
| 89 | * @since 3.0.0 |
||
| 90 | * |
||
| 91 | * @param Notice $notice |
||
| 92 | * |
||
| 93 | * @return void |
||
| 94 | */ |
||
| 95 | public function add_notice( $notice ) { |
||
| 112 | |||
| 113 | /** |
||
| 114 | * Dismiss a notice. |
||
| 115 | * |
||
| 116 | * @TODO Improve notice dismissal with ajax. |
||
| 117 | * |
||
| 118 | * @since 3.0.0 |
||
| 119 | * |
||
| 120 | * @param string $notice (optional) The notice id. |
||
| 121 | * |
||
| 122 | * @return void |
||
| 123 | */ |
||
| 124 | public function remove_notice( $notice = '' ) { |
||
| 147 | |||
| 148 | /** |
||
| 149 | * Show a notice. |
||
| 150 | * |
||
| 151 | * @since 3.0.0 |
||
| 152 | * |
||
| 153 | * @param string $notice |
||
| 154 | * |
||
| 155 | * @return void |
||
| 156 | */ |
||
| 157 | View Code Duplication | public function show_notice( $notice ) { |
|
| 158 | |||
| 159 | $notices = $this->get_notices(); |
||
| 160 | |||
| 161 | if ( isset( $notices[ $notice ]->visible ) ) { |
||
| 162 | $notices[ $notice ]->visible = true; |
||
| 163 | update_option( 'simple-calendar_admin_notices', $notices ); |
||
| 164 | } |
||
| 165 | } |
||
| 166 | |||
| 167 | /** |
||
| 168 | * Hide a notice. |
||
| 169 | * |
||
| 170 | * @since 3.0.0 |
||
| 171 | * |
||
| 172 | * @param string $notice |
||
| 173 | * |
||
| 174 | * @return void |
||
| 175 | */ |
||
| 176 | View Code Duplication | public function hide_notice( $notice ) { |
|
| 177 | |||
| 178 | $notices = $this->get_notices(); |
||
| 179 | |||
| 180 | if ( isset( $notices[ $notice ]->visible ) ) { |
||
| 181 | $notices[ $notice ]->visible = false; |
||
| 182 | update_option( 'simple-calendar_admin_notices', $notices ); |
||
| 183 | } |
||
| 184 | } |
||
| 185 | |||
| 186 | /** |
||
| 187 | * Get current notices. |
||
| 188 | * |
||
| 189 | * @since 3.0.0 |
||
| 190 | * |
||
| 191 | * @return array |
||
| 192 | */ |
||
| 193 | public function get_notices() { |
||
| 199 | |||
| 200 | } |
||
| 201 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: