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 |
||
24 | final class Card extends Api |
||
25 | { |
||
26 | /** |
||
27 | * @param string $customerId |
||
28 | * @param string $cardId |
||
29 | * |
||
30 | * @return string |
||
31 | */ |
||
32 | private static function path($customerId, $cardId) |
||
36 | |||
37 | /** |
||
38 | * @param Customer $customer |
||
39 | * @param array $parameters |
||
40 | * |
||
41 | * @return Pagination |
||
42 | */ |
||
43 | public function all(Customer $customer, array $parameters = []) |
||
49 | |||
50 | /** |
||
51 | * @param string $customerId |
||
52 | * @param string $id |
||
53 | * |
||
54 | * @return Domain |
||
55 | */ |
||
56 | public function find($customerId, $id) |
||
62 | |||
63 | /** |
||
64 | * @param Domain $card |
||
65 | */ |
||
66 | public function refresh(Domain $card) |
||
70 | |||
71 | /** |
||
72 | * @param Domain $card |
||
73 | */ |
||
74 | View Code Duplication | public function update(Domain $card) |
|
82 | |||
83 | /** |
||
84 | * @param Domain $card |
||
85 | */ |
||
86 | View Code Duplication | public function destroy(Domain $card) |
|
94 | } |
||
95 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: