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 |
||
18 | class JailObject implements \ArrayAccess |
||
19 | { |
||
20 | /** |
||
21 | * @var string[] |
||
22 | */ |
||
23 | private $whiteListFunctions; |
||
24 | |||
25 | /** |
||
26 | * @var string[] |
||
27 | */ |
||
28 | private $jailedFunctions; |
||
29 | |||
30 | /** |
||
31 | * @var Jailable |
||
32 | */ |
||
33 | private $object; |
||
34 | |||
35 | /** |
||
36 | * JailObject constructor. |
||
37 | * |
||
38 | * @param Jailable $object The object that will be jailed |
||
39 | * @param array $whiteListFunctions A list of function names that can be called |
||
40 | * @param array $jailedFunctions |
||
41 | */ |
||
42 | 4 | public function __construct (&$object, array $whiteListFunctions, array $jailedFunctions = array()) |
|
43 | { |
||
44 | 4 | if (!($object instanceof Jailable) && !($object instanceof \ArrayAccess)) |
|
45 | 4 | { |
|
46 | throw new \InvalidArgumentException('Must implement the ArrayAccess and Jailable interfaces'); |
||
47 | } |
||
48 | |||
49 | 4 | $this->object = &$object; |
|
50 | 4 | $this->whiteListFunctions = $whiteListFunctions; |
|
51 | 4 | $this->jailedFunctions = $jailedFunctions; |
|
52 | 4 | } |
|
53 | |||
54 | 3 | public function __call ($name, $arguments) |
|
83 | |||
84 | 1 | public function __get ($name) |
|
93 | |||
94 | public function coreInstanceOf ($class) |
||
98 | |||
99 | // |
||
100 | // ArrayAccess Implementation |
||
101 | // |
||
102 | |||
103 | /** |
||
104 | * {@inheritdoc} |
||
105 | */ |
||
106 | 1 | public function offsetExists($offset) |
|
110 | |||
111 | /** |
||
112 | * {@inheritdoc} |
||
113 | */ |
||
114 | 1 | public function offsetGet($offset) |
|
118 | |||
119 | /** |
||
120 | * {@inheritdoc} |
||
121 | */ |
||
122 | public function offsetSet($offset, $value) |
||
126 | |||
127 | /** |
||
128 | * {@inheritdoc} |
||
129 | */ |
||
130 | public function offsetUnset($offset) |
||
134 | } |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.