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 |
||
| 15 | class SQLServerQuery extends Query |
||
| 16 | { |
||
| 17 | |||
| 18 | /** |
||
| 19 | * The SQLServerConnector object that created this result set. |
||
| 20 | * |
||
| 21 | * @var SQLServerConnector |
||
| 22 | */ |
||
| 23 | protected $connector; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * The internal MSSQL handle that points to the result set. |
||
| 27 | * |
||
| 28 | * @var resource |
||
| 29 | */ |
||
| 30 | protected $handle; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Hook the result-set given into a Query class, suitable for use by sapphire. |
||
| 34 | * @param SQLServerConnector $connector The database object that created this query. |
||
| 35 | * @param resource $handle the internal mssql handle that is points to the resultset. |
||
| 36 | */ |
||
| 37 | public function __construct(SQLServerConnector $connector, $handle) |
||
| 42 | |||
| 43 | public function __destruct() |
||
| 49 | |||
| 50 | public function numRecords() |
||
| 63 | |||
| 64 | View Code Duplication | public function nextRecord() |
|
| 74 | |||
| 75 | View Code Duplication | public function seek($row) |
|
| 85 | } |
||
| 86 |
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.