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 Holding extends LazyResource |
||
| 14 | { |
||
| 15 | /* @var string */ |
||
| 16 | public $holding_id; |
||
| 17 | |||
| 18 | /* @var Bib */ |
||
| 19 | public $bib; |
||
| 20 | |||
| 21 | /* @var Items */ |
||
| 22 | public $items; |
||
| 23 | |||
| 24 | /* @var MarcRecord */ |
||
| 25 | protected $_marc; |
||
| 26 | |||
| 27 | public function __construct(Client $client, Bib $bib, $holding_id) |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Get the model data. |
||
| 37 | */ |
||
| 38 | protected function fetchData() |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Check if we have the full representation of our data object. |
||
| 45 | * |
||
| 46 | * @param $data |
||
| 47 | * |
||
| 48 | * @return bool |
||
| 49 | */ |
||
| 50 | protected function isInitialized($data) |
||
| 54 | |||
| 55 | /** |
||
| 56 | * Update the MARC record on this holding object. Chainable method. |
||
| 57 | * |
||
| 58 | * @param string $xml |
||
| 59 | * |
||
| 60 | * @return Holding |
||
| 61 | */ |
||
| 62 | public function setMarcRecord($xml) |
||
| 68 | |||
| 69 | |||
| 70 | /** |
||
| 71 | * Save the holding. |
||
| 72 | */ |
||
| 73 | View Code Duplication | public function save() |
|
| 82 | |||
| 83 | /** |
||
| 84 | * Called when data is available to be processed. |
||
| 85 | * |
||
| 86 | * @param mixed $data |
||
| 87 | */ |
||
| 88 | protected function onData($data) |
||
| 92 | |||
| 93 | /** |
||
| 94 | * Generate the base URL for this resource. |
||
| 95 | * |
||
| 96 | * @return string |
||
| 97 | */ |
||
| 98 | protected function urlBase() |
||
| 102 | |||
| 103 | /** |
||
| 104 | * Get the MARC record for this holding object. |
||
| 105 | */ |
||
| 106 | public function getRecord() |
||
| 110 | |||
| 111 | /** |
||
| 112 | * Get the items for this holding. |
||
| 113 | */ |
||
| 114 | public function getItems() |
||
| 118 | } |
||
| 119 |
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.