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 |
||
| 12 | class Driver extends Serializer |
||
| 13 | { |
||
| 14 | /** |
||
| 15 | * |
||
| 16 | */ |
||
| 17 | public function __construct() |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @param mixed $value |
||
| 23 | * |
||
| 24 | * @return mixed|string |
||
| 25 | */ |
||
| 26 | public function serialize($value) |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Extract the data from an object. |
||
| 35 | * |
||
| 36 | * @param mixed $value |
||
| 37 | * |
||
| 38 | * @return array |
||
| 39 | */ |
||
| 40 | protected function serializeObject($value) |
||
| 56 | |||
| 57 | /** |
||
| 58 | * @param Collection $value |
||
| 59 | * |
||
| 60 | * @return array |
||
| 61 | */ |
||
| 62 | View Code Duplication | protected function serializeEloquentCollection(Collection $value) |
|
| 71 | |||
| 72 | /** |
||
| 73 | * @param Paginator $value |
||
| 74 | * |
||
| 75 | * @return array |
||
| 76 | */ |
||
| 77 | View Code Duplication | protected function serializeEloquentPaginatedResource(Paginator $value) |
|
| 86 | |||
| 87 | /** |
||
| 88 | * @param Model $value |
||
| 89 | * |
||
| 90 | * @return array |
||
| 91 | */ |
||
| 92 | protected function serializeEloquentModel(Model $value) |
||
| 111 | } |
||
| 112 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_functionexpects aPostobject, and outputs the author of the post. The base classPostreturns a simple string and outputting a simple string will work just fine. However, the child classBlogPostwhich is a sub-type ofPostinstead decided to return anobject, and is therefore violating the SOLID principles. If aBlogPostwere passed tomy_function, PHP would not complain, but ultimately fail when executing thestrtouppercall in its body.