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 |
||
29 | class TraceableNetwork extends AbstractNetworkAdapter implements NetworkAdapterinterface |
||
30 | { |
||
31 | const TYPE_DATA = 'data'; |
||
32 | const TYPE_CONNECT = 'connect'; |
||
33 | const TYPE_DISCONNECT = 'disconnect'; |
||
34 | const TYPE_BEGIN_GROUP = 'begin.group'; |
||
35 | const TYPE_END_GROUP = 'end.group'; |
||
36 | |||
37 | /** |
||
38 | * @var array |
||
39 | */ |
||
40 | private $actions; |
||
41 | |||
42 | /** |
||
43 | * @var LoggerInterface |
||
44 | */ |
||
45 | private $logger; |
||
46 | |||
47 | /** |
||
48 | * TraceableNetwork constructor. |
||
49 | * |
||
50 | * @param NetworkInterface $network |
||
51 | * @param LoggerInterface $logger |
||
52 | */ |
||
53 | 2 | public function __construct(NetworkInterface $network, LoggerInterface $logger) |
|
68 | |||
69 | /** |
||
70 | * Wrap the creation of the callback |
||
71 | * |
||
72 | * @return \Closure |
||
73 | */ |
||
74 | private function trace($type) |
||
90 | |||
91 | /** |
||
92 | * @param array $args |
||
93 | * @param string $type |
||
94 | */ |
||
95 | private function traceData(array $args, $type) |
||
114 | |||
115 | /** |
||
116 | * @param array $args |
||
117 | * @param string $type |
||
118 | */ |
||
119 | private function traceAction(array $args, $type) |
||
133 | } |
||
134 |
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: