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 |
||
| 17 | class TransformedFinder implements PaginatedFinderInterface |
||
| 18 | { |
||
| 19 | protected $searchable; |
||
| 20 | protected $transformer; |
||
| 21 | |||
| 22 | public function __construct(SearchableInterface $searchable, ElasticaToModelTransformerInterface $transformer) |
||
| 27 | |||
| 28 | /** |
||
| 29 | * Search for a query string. |
||
| 30 | * |
||
| 31 | * @param string $query |
||
| 32 | * @param integer $limit |
||
| 33 | * @param array $options |
||
| 34 | * |
||
| 35 | * @return array of model objects |
||
| 36 | **/ |
||
| 37 | public function find($query, $limit = null, $options = array()) |
||
| 43 | |||
| 44 | public function findHybrid($query, $limit = null, $options = array()) |
||
| 50 | |||
| 51 | public function findRawResult($query, $limit = null, $options = array()) |
||
| 57 | /** |
||
| 58 | * Find documents similar to one with passed id. |
||
| 59 | * |
||
| 60 | * @param integer $id |
||
| 61 | * @param array $params |
||
| 62 | * @param array $query |
||
| 63 | * |
||
| 64 | * @return array of model objects |
||
| 65 | **/ |
||
| 66 | public function moreLikeThis($id, $params = array(), $query = array()) |
||
| 73 | |||
| 74 | /** |
||
| 75 | * @param $query |
||
| 76 | * @param null|int $limit |
||
| 77 | * @param array $options |
||
| 78 | * |
||
| 79 | * @return array |
||
| 80 | */ |
||
| 81 | protected function search($query, $limit = null, $options = array()) |
||
| 91 | |||
| 92 | /** |
||
| 93 | * Gets a paginator wrapping the result of a search. |
||
| 94 | * |
||
| 95 | * @param string $query |
||
| 96 | * @param array $options |
||
| 97 | * |
||
| 98 | * @return Pagerfanta |
||
| 99 | */ |
||
| 100 | View Code Duplication | public function findPaginated($query, $options = array()) |
|
| 107 | |||
| 108 | /** |
||
| 109 | * {@inheritdoc} |
||
| 110 | */ |
||
| 111 | View Code Duplication | public function findRawPaginated($query, $options = array()) |
|
| 118 | |||
| 119 | /** |
||
| 120 | * {@inheritdoc} |
||
| 121 | */ |
||
| 122 | public function createPaginatorAdapter($query, $options = array()) |
||
| 128 | |||
| 129 | /** |
||
| 130 | * {@inheritdoc} |
||
| 131 | */ |
||
| 132 | public function createRawPaginatorAdapter($query, $options = array()) |
||
| 137 | } |
||
| 138 |
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: