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_Jetpack_Admin_Menu extends WP_UnitTestCase { |
||
20 | |||
21 | /** |
||
22 | * Menu data fixture. |
||
23 | * |
||
24 | * @var array |
||
25 | */ |
||
26 | public static $menu_data; |
||
27 | |||
28 | /** |
||
29 | * Submenu data fixture. |
||
30 | * |
||
31 | * @var array |
||
32 | */ |
||
33 | public static $submenu_data; |
||
34 | |||
35 | /** |
||
36 | * Test domain. |
||
37 | * |
||
38 | * @var string |
||
39 | */ |
||
40 | public static $domain; |
||
41 | |||
42 | /** |
||
43 | * Whether this testsuite is run on WP.com. |
||
44 | * |
||
45 | * @var bool |
||
46 | */ |
||
47 | public static $is_wpcom; |
||
48 | |||
49 | /** |
||
50 | * Admin menu instance. |
||
51 | * |
||
52 | * @var Jetpack_Admin_Menu |
||
53 | */ |
||
54 | public static $admin_menu; |
||
55 | |||
56 | /** |
||
57 | * Mock user ID. |
||
58 | * |
||
59 | * @var int |
||
60 | */ |
||
61 | private static $user_id = 0; |
||
62 | |||
63 | /** |
||
64 | * Create shared fixtures. |
||
65 | * |
||
66 | * @param WP_UnitTest_Factory $factory Fixture factory. |
||
67 | */ |
||
68 | View Code Duplication | public static function wpSetUpBeforeClass( $factory ) { |
|
75 | |||
76 | /** |
||
77 | * Set up data. |
||
78 | */ |
||
79 | View Code Duplication | public function setUp() { |
|
91 | |||
92 | /** |
||
93 | * Tests add_jetpack_menu |
||
94 | * |
||
95 | * @covers ::add_jetpack_menu |
||
96 | */ |
||
97 | public function test_add_jetpack_menu() { |
||
98 | global $submenu; |
||
99 | |||
100 | static::$admin_menu->add_jetpack_menu(); |
||
101 | |||
102 | $domains_submenu_item = array( |
||
103 | 'Scan', |
||
104 | 'manage_options', |
||
105 | 'https://wordpress.com/scan/' . static::$domain, |
||
106 | 'Scan', |
||
107 | ); |
||
108 | $this->assertContains( $domains_submenu_item, $submenu[ 'https://wordpress.com/activity-log/' . static::$domain ] ); |
||
109 | } |
||
110 | |||
111 | /** |
||
112 | * Tests add_tools_menu |
||
113 | * |
||
114 | * @covers ::add_tools_menu |
||
115 | */ |
||
116 | public function test_add_tools_menu() { |
||
140 | |||
141 | /** |
||
142 | * Tests add_wp_admin_menu |
||
143 | * |
||
144 | * @covers ::add_wp_admin_menu |
||
145 | */ |
||
146 | public function test_add_wp_admin_menu() { |
||
162 | } |
||
163 |
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
SomeClass
to useself
instead: