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 |
||
| 11 | class ResultObjectMapper implements ResultObjectMapperInterface |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * Map each item in response data to instance of ResultObjectInterface |
||
| 15 | * @param array $response |
||
| 16 | * @param MethodResultCollectionInterface $method |
||
| 17 | * |
||
| 18 | * @return array |
||
| 19 | */ |
||
| 20 | public function mapCollection(array $response, MethodResultCollectionInterface $method) |
||
| 30 | |||
| 31 | /** |
||
| 32 | * Map response data to instance of ResultObjectInterface |
||
| 33 | * @param array $response |
||
| 34 | * @param ResultObjectInterface $result |
||
| 35 | * |
||
| 36 | * @return ResultObjectInterface |
||
| 37 | */ |
||
| 38 | public function map(array $response, ResultObjectInterface $result) |
||
| 61 | |||
| 62 | /** |
||
| 63 | * Extracts camelCased setter name from underscore notation. |
||
| 64 | * Eg. my_field_name => myFieldName |
||
| 65 | * @param string $field |
||
| 66 | * @return string |
||
| 67 | */ |
||
| 68 | View Code Duplication | private function getSetterName($field) |
|
| 76 | |||
| 77 | /** |
||
| 78 | * Transform PaymentInstrument result array to object |
||
| 79 | * @param array $data |
||
| 80 | * @param string $method |
||
| 81 | * @return PaymentInstrumentCard|PaymentInstrumentRecurring |
||
| 82 | * @throws Exception\Runtime for unsupported methods |
||
| 83 | */ |
||
| 84 | private function transformPaymentInstrumentValue(array $data, $method) |
||
| 98 | |||
| 99 | /** |
||
| 100 | * Transform AuthorizationInformation result array to object |
||
| 101 | * @param array $data |
||
| 102 | * @return AuthorizationInformation |
||
| 103 | */ |
||
| 104 | private function transformAuthorizationInformationValue($data) |
||
| 111 | |||
| 112 | /** |
||
| 113 | * @param ARRAY $data |
||
| 114 | * @return ThreeDS2AuthorizationInformation |
||
| 115 | */ |
||
| 116 | private function transformThreeDS2DataValue($data) |
||
| 122 | } |
||
| 123 |
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: