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 WebTranslateItRepository implements TranslationRepositoryInterface |
||
13 | { |
||
14 | const FORMAT_JSON = 'json'; |
||
15 | const PULL_PROJECT_URL_PATTERN = '{base_url}projects/{token}.{format}'; |
||
16 | const PULL_FILE_URL_PATTERN = '{base_url}projects/{token}/files/...?file_path={name}'; |
||
17 | |||
18 | /** |
||
19 | * @var string |
||
20 | */ |
||
21 | private $readKey; |
||
22 | |||
23 | /** |
||
24 | * @var string |
||
25 | */ |
||
26 | private $baseUrl; |
||
27 | |||
28 | /** |
||
29 | * @var SerializerInterface |
||
30 | */ |
||
31 | private $serializer; |
||
32 | |||
33 | /** |
||
34 | * @var Client |
||
35 | */ |
||
36 | private $client; |
||
37 | |||
38 | /** |
||
39 | * WebTranslateItRepository constructor. |
||
40 | * |
||
41 | * @param string $readKey |
||
42 | * @param string $baseUrl |
||
43 | * @param Client $client |
||
44 | * @param SerializerInterface $serializer |
||
45 | */ |
||
46 | public function __construct( |
||
57 | |||
58 | /** |
||
59 | * {@inheritdoc} |
||
60 | */ |
||
61 | public function pullProject() |
||
70 | |||
71 | /** |
||
72 | * {@inheritdoc} |
||
73 | */ |
||
74 | public function pullFile($name) |
||
82 | |||
83 | /** |
||
84 | * @return string |
||
85 | */ |
||
86 | View Code Duplication | private function getPullProjectUrl() |
|
94 | |||
95 | /** |
||
96 | * @param string $name |
||
97 | * |
||
98 | * @return string |
||
99 | */ |
||
100 | View Code Duplication | private function getPullFileUrl($name) |
|
108 | } |
||
109 |
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_function
expects aPost
object, and outputs the author of the post. The base classPost
returns a simple string and outputting a simple string will work just fine. However, the child classBlogPost
which is a sub-type ofPost
instead decided to return anobject
, and is therefore violating the SOLID principles. If aBlogPost
were passed tomy_function
, PHP would not complain, but ultimately fail when executing thestrtoupper
call in its body.