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 | abstract class AbstractColumn { |
||
| 14 | |||
| 15 | use EscapeTrait; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * @var \donatj\MySqlSchema\Table[] |
||
| 19 | */ |
||
| 20 | protected $tables = [ ]; |
||
| 21 | /** |
||
| 22 | * @var string |
||
| 23 | */ |
||
| 24 | protected $name; |
||
| 25 | /** |
||
| 26 | * @var string |
||
| 27 | */ |
||
| 28 | protected $comment = ''; |
||
| 29 | /** |
||
| 30 | * @var bool |
||
| 31 | */ |
||
| 32 | protected $nullable = false; |
||
| 33 | /** |
||
| 34 | * @var mixed |
||
| 35 | */ |
||
| 36 | protected $default; |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @param string $name |
||
| 40 | */ |
||
| 41 | public function __construct( $name ) { |
||
| 44 | |||
| 45 | /** |
||
| 46 | * @access private |
||
| 47 | * @param \donatj\MySqlSchema\Table $table |
||
| 48 | */ |
||
| 49 | public function addTable( Table $table ) { |
||
| 52 | |||
| 53 | /** |
||
| 54 | * @return \donatj\MySqlSchema\Table[] |
||
| 55 | */ |
||
| 56 | public function getTables() { |
||
| 59 | |||
| 60 | /** |
||
| 61 | * @return string |
||
| 62 | */ |
||
| 63 | public function getComment() { |
||
| 66 | |||
| 67 | /** |
||
| 68 | * @param string $comment |
||
| 69 | */ |
||
| 70 | public function setComment( $comment ) { |
||
| 73 | |||
| 74 | /** |
||
| 75 | * @return boolean |
||
| 76 | */ |
||
| 77 | public function isNullable() { |
||
| 80 | |||
| 81 | /** |
||
| 82 | * @param boolean $nullable |
||
| 83 | */ |
||
| 84 | public function setNullable( $nullable ) { |
||
| 87 | |||
| 88 | /** |
||
| 89 | * @return string |
||
| 90 | */ |
||
| 91 | public function getName() { |
||
| 94 | |||
| 95 | /** |
||
| 96 | * @param string $name |
||
| 97 | */ |
||
| 98 | public function setName( $name ) { |
||
| 101 | |||
| 102 | /** |
||
| 103 | * @param \donatj\MySqlSchema\Table $table |
||
| 104 | * @return string |
||
| 105 | */ |
||
| 106 | public function toString( Table $table ) { |
||
| 161 | |||
| 162 | /** |
||
| 163 | * @return string |
||
| 164 | */ |
||
| 165 | abstract public function getTypeName(); |
||
| 166 | |||
| 167 | /** |
||
| 168 | * @return mixed |
||
| 169 | */ |
||
| 170 | public function getDefault() { |
||
| 173 | |||
| 174 | /** |
||
| 175 | * @param mixed $default |
||
| 176 | */ |
||
| 177 | public function setDefault( $default ) { |
||
| 180 | } |
||
| 181 |
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 sub-classes 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 parent class: