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 |
||
| 14 | class FieldTest extends BaseTest |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * Tests the Field parser. |
||
| 18 | */ |
||
| 19 | public function testParse() |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Test Field parser throwing exception on missing sort clause. |
||
| 40 | * |
||
| 41 | * @expectedException \eZ\Publish\Core\REST\Common\Exceptions\Parser |
||
| 42 | * @expectedExceptionMessage The <Field> sort clause doesn't exist in the input structure |
||
| 43 | */ |
||
| 44 | public function testParseExceptionOnMissingSortClause() |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Test Field parser throwing exception on invalid direction format. |
||
| 56 | * |
||
| 57 | * @expectedException \eZ\Publish\Core\REST\Common\Exceptions\Parser |
||
| 58 | * @expectedExceptionMessage Invalid direction format in <Field> sort clause |
||
| 59 | */ |
||
| 60 | View Code Duplication | public function testParseExceptionOnInvalidDirectionFormat() |
|
| 72 | |||
| 73 | /** |
||
| 74 | * Returns the Field parser. |
||
| 75 | * |
||
| 76 | * @return \eZ\Publish\Core\REST\Server\Input\Parser\SortClause\Field |
||
| 77 | */ |
||
| 78 | protected function internalGetParser() |
||
| 82 | } |
||
| 83 |
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.