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 |
||
7 | View Code Duplication | trait HasLinks |
|
8 | { |
||
9 | /** |
||
10 | * Get a model from a relationship by model name. |
||
11 | * |
||
12 | * @param string $relationship Name of relationship. |
||
13 | * @param string $name Name of model to get. |
||
14 | * |
||
15 | * @return \Illuminate\Database\Eloquent\Model|null |
||
16 | */ |
||
17 | abstract protected function getFromRelationshipByName($relationship, $name); |
||
18 | |||
19 | /** |
||
20 | * A resource has many text blocks. |
||
21 | * |
||
22 | * @return MorphMany |
||
23 | */ |
||
24 | public function links() |
||
28 | |||
29 | /** |
||
30 | * Return true if project has links. |
||
31 | * |
||
32 | * @return bool |
||
33 | */ |
||
34 | public function hasLinks() |
||
38 | |||
39 | /** |
||
40 | * Get link by name, if exists. |
||
41 | * |
||
42 | * @param string $name Name of link to get. |
||
43 | * |
||
44 | * @return Larafolio\Models\Link|null |
||
45 | */ |
||
46 | public function link($name) |
||
50 | |||
51 | /** |
||
52 | * Get link url. |
||
53 | * |
||
54 | * @param string $name Name of link. |
||
55 | * |
||
56 | * @return string|null |
||
57 | */ |
||
58 | public function linkUrl($name) |
||
66 | |||
67 | /** |
||
68 | * Get link text. |
||
69 | * |
||
70 | * @param string $name Name of link. |
||
71 | * |
||
72 | * @return string|null |
||
73 | */ |
||
74 | public function linkText($name) |
||
82 | } |
||
83 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: