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 |
||
| 21 | class SilexUserServiceProviderConfigurationTest extends WebTestCase |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * @expectedException LogicException |
||
| 25 | * @expectedExceptionMessage The "user_class" option must be set |
||
| 26 | */ |
||
| 27 | public function testWithoutUserClass() |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @expectedException LogicException |
||
| 34 | * @expectedExceptionMessage The "user_class" option must be set |
||
| 35 | */ |
||
| 36 | public function testWithEmptyUserClass() |
||
| 44 | |||
| 45 | /** |
||
| 46 | * @expectedException LogicException |
||
| 47 | * @expectedExceptionMessage The "firewall_name" option must be set |
||
| 48 | */ |
||
| 49 | public function testWithoutFirewallName() |
||
| 57 | |||
| 58 | /** |
||
| 59 | * @expectedException LogicException |
||
| 60 | * @expectedExceptionMessage The "firewall_name" option must be set |
||
| 61 | */ |
||
| 62 | public function testWithEmptyFirewallName() |
||
| 71 | |||
| 72 | /** |
||
| 73 | * @expectedException LogicException |
||
| 74 | * @expectedExceptionMessage You must configure a mailer to enable email notifications |
||
| 75 | */ |
||
| 76 | public function testEmailConfirmationWithoutMailer() |
||
| 86 | |||
| 87 | /** |
||
| 88 | * @expectedException LogicException |
||
| 89 | * @expectedExceptionMessage The "registration.confirmation.from_email" option must be set |
||
| 90 | */ |
||
| 91 | View Code Duplication | public function testEmailConfirmationWithoutFromEmail() |
|
| 103 | |||
| 104 | /** |
||
| 105 | * @expectedException LogicException |
||
| 106 | * @expectedExceptionMessage The "registration.confirmation.from_email" option must be set |
||
| 107 | */ |
||
| 108 | View Code Duplication | public function testEmailConfirmationWithEmptyFromEmail() |
|
| 121 | |||
| 122 | public function createApplication() |
||
| 148 | } |
||
| 149 |
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: