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 |
||
13 | class Doctrine extends AbstractTable |
||
14 | { |
||
15 | |||
16 | protected $config = array( |
||
17 | 'name' => 'Doctrine 2', |
||
18 | 'showPagination' => true, |
||
19 | 'showQuickSearch' => false, |
||
20 | 'showItemPerPage' => true, |
||
21 | 'showColumnFilters' => true, |
||
22 | ); |
||
23 | |||
24 | /** |
||
25 | * @var array Definition of headers |
||
26 | */ |
||
27 | protected $headers = array( |
||
28 | 'idcustomer' => array('tableAlias' => 'q', 'title' => 'Id', 'width' => '50') , |
||
29 | 'doctrine' => array( |
||
30 | 'tableAlias' => 'q', |
||
31 | 'title' => 'Doctrine closure' , |
||
32 | 'filters' => 'text', |
||
33 | 'sortable' => false |
||
34 | ), |
||
35 | 'product' => array('tableAlias' => 'p', 'title' => 'Product', 'filters' => 'text'), |
||
36 | 'name' => array('tableAlias' => 'q', 'title' => 'Name', 'filters' => 'text') , |
||
37 | 'surname' => array('tableAlias' => 'q', 'title' => 'Surname', 'filters' => 'text'), |
||
38 | 'street' => array('tableAlias' => 'q', 'title' => 'Street', 'filters' => 'text'), |
||
39 | 'city' => array('tableAlias' => 'q', 'title' => 'City', 'filters' => 'text'), |
||
40 | 'active' => array('tableAlias' => 'q', 'title' => 'Active', 'width' => 100 ), |
||
41 | ); |
||
42 | |||
43 | public function init() |
||
63 | |||
64 | //The filters could also be done with a parametrised query |
||
65 | protected function initFilters($query) |
||
95 | } |
||
96 |
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: