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 |
||
| 17 | class Test_Base_Admin_Menu extends WP_UnitTestCase { |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Admin menu instance. |
||
| 21 | * |
||
| 22 | * @var Base_Admin_Menu |
||
| 23 | */ |
||
| 24 | public static $admin_menu; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * Mock user ID. |
||
| 28 | * |
||
| 29 | * @var int |
||
| 30 | */ |
||
| 31 | private static $user_id = 0; |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Menu data fixture. |
||
| 35 | * |
||
| 36 | * @var array |
||
| 37 | */ |
||
| 38 | public static $menu_data; |
||
| 39 | |||
| 40 | /** |
||
| 41 | * Submenu data fixture. |
||
| 42 | * |
||
| 43 | * @var array |
||
| 44 | */ |
||
| 45 | public static $submenu_data; |
||
| 46 | |||
| 47 | /** |
||
| 48 | * Create shared fixtures. |
||
| 49 | * |
||
| 50 | * @param WP_UnitTest_Factory $factory Fixture factory. |
||
| 51 | */ |
||
| 52 | public static function wpSetUpBeforeClass( $factory ) { |
||
| 57 | |||
| 58 | /** |
||
| 59 | * Set up data. |
||
| 60 | */ |
||
| 61 | public function setUp() { |
||
| 71 | |||
| 72 | /** |
||
| 73 | * Test get_instance. |
||
| 74 | * |
||
| 75 | * @covers ::get_instance |
||
| 76 | * @covers ::__construct |
||
| 77 | */ |
||
| 78 | View Code Duplication | public function test_get_instance() { |
|
| 90 | |||
| 91 | /** |
||
| 92 | * Tests add_admin_menu_separator |
||
| 93 | * |
||
| 94 | * @covers ::add_admin_menu_separator |
||
| 95 | */ |
||
| 96 | public function test_add_admin_menu_separator() { |
||
| 115 | |||
| 116 | /** |
||
| 117 | * Get an object of Base_Admin_Menu |
||
| 118 | * |
||
| 119 | * @return Base_Admin_Menu |
||
| 120 | */ |
||
| 121 | private function get_concrete_menu_admin() { |
||
| 124 | } |
||
| 125 |
Let’s assume you have a class which uses late-static binding:
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClassto useselfinstead: