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 |
||
| 19 | class Test_Domain_Only_Admin_Menu extends WP_UnitTestCase { |
||
| 20 | |||
| 21 | /** |
||
| 22 | * Menu data fixture. |
||
| 23 | * |
||
| 24 | * @var array |
||
| 25 | */ |
||
| 26 | public static $menu_data; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * Test domain. |
||
| 30 | * |
||
| 31 | * @var string |
||
| 32 | */ |
||
| 33 | public static $domain; |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Admin menu instance. |
||
| 37 | * |
||
| 38 | * @var Domain_Only_Admin_Menu |
||
| 39 | */ |
||
| 40 | public static $admin_menu; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * Mock user ID. |
||
| 44 | * |
||
| 45 | * @var int |
||
| 46 | */ |
||
| 47 | private static $user_id = 0; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * Create shared fixtures. |
||
| 51 | * |
||
| 52 | * @param WP_UnitTest_Factory $factory Fixture factory. |
||
| 53 | */ |
||
| 54 | public static function wpSetUpBeforeClass( $factory ) { |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Set up data. |
||
| 62 | */ |
||
| 63 | View Code Duplication | public function setUp() { |
|
| 74 | |||
| 75 | /** |
||
| 76 | * Tests reregister_menu_items. |
||
| 77 | * |
||
| 78 | * @covers ::reregister_menu_items |
||
| 79 | */ |
||
| 80 | public function test_reregister_menu_items() { |
||
| 88 | } |
||
| 89 |
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: