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 SilexUserServiceProviderDependenciesTest extends WebTestCase |
||
20 | { |
||
21 | /** |
||
22 | * @expectedException LogicException |
||
23 | * @expectedExceptionMessage You must register the ServiceControllerServiceProvider to use the SilexUserServiceProvider |
||
24 | */ |
||
25 | public function testRegisterWithoutServiceController() |
||
29 | |||
30 | /** |
||
31 | * @expectedException LogicException |
||
32 | * @expectedExceptionMessage You must register the TwigServiceProvider to use the SilexUserServiceProvider |
||
33 | */ |
||
34 | public function testRegisterWithoutTwig() |
||
39 | |||
40 | /** |
||
41 | * @expectedException LogicException |
||
42 | * @expectedExceptionMessage You must register the SessionServiceProvider to use the SilexUserServiceProvider |
||
43 | */ |
||
44 | public function testRegisterWithoutSession() |
||
50 | |||
51 | /** |
||
52 | * @expectedException LogicException |
||
53 | * @expectedExceptionMessage You must register the TranslationServiceProvider to use the SilexUserServiceProvider |
||
54 | */ |
||
55 | public function testRegisterWitoutTranslation() |
||
62 | |||
63 | /** |
||
64 | * @expectedException LogicException |
||
65 | * @expectedExceptionMessage You must register the ValidatorServiceProvider to use the SilexUserServiceProvider |
||
66 | */ |
||
67 | public function testRegisterWitoutValidator() |
||
76 | |||
77 | /** |
||
78 | * @expectedException LogicException |
||
79 | * @expectedExceptionMessage You must register the FormServiceProvider to use the SilexUserServiceProvider |
||
80 | */ |
||
81 | View Code Duplication | public function testRegisterWitoutForm() |
|
91 | |||
92 | /** |
||
93 | * @expectedException LogicException |
||
94 | * @expectedExceptionMessage You must register the DoctrineOrmServiceProvider to use the SilexUserServiceProvider |
||
95 | */ |
||
96 | View Code Duplication | public function testRegisterWitoutDoctrineOrm() |
|
107 | |||
108 | /** |
||
109 | * @expectedException LogicException |
||
110 | * @expectedExceptionMessage You must register the SecurityServiceProvider to use the SilexUserServiceProvider |
||
111 | */ |
||
112 | public function tetRegisterWitoutSecurity() |
||
126 | |||
127 | public function createApplication() |
||
135 | } |
||
136 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: