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 |
||
8 | class Paystack |
||
9 | { |
||
10 | public $secret_key; |
||
11 | public $use_guzzle = false; |
||
12 | |||
13 | 14 | public function __construct($secret_key) |
|
20 | |||
21 | 1 | public function useGuzzle() |
|
25 | |||
26 | 4 | public function __call($method, $args) |
|
27 | { |
||
28 | 4 | if ($singular_form = Router::singularFor($method)) { |
|
29 | 1 | return $this->handlePlural($singular_form, $method, $args); |
|
30 | } |
||
31 | 3 | return $this->handleSingular($method, $args); |
|
32 | } |
||
33 | |||
34 | 1 | private function handlePlural($singular_form, $method, $args) |
|
35 | { |
||
36 | 1 | if ((count($args) === 1 && is_array($args[0]))||(count($args) === 0)) { |
|
37 | return $this->{$singular_form}->__call('getList', $args); |
||
38 | } |
||
39 | 1 | throw new \InvalidArgumentException( |
|
40 | 1 | 'Route "' . $method . '" can only accept an optional array of filters and ' |
|
41 | 1 | .'paging arguments (perPage, page).' |
|
42 | 1 | ); |
|
43 | } |
||
44 | |||
45 | 3 | private function handleSingular($method, $args) |
|
46 | { |
||
47 | 3 | if (count($args) === 1) { |
|
48 | 1 | $args = [[], [ Router::ID_KEY => $args[0] ] ]; |
|
49 | 1 | return $this->{$method}->__call('fetch', $args); |
|
50 | } |
||
51 | 2 | throw new \InvalidArgumentException( |
|
52 | 2 | 'Route "' . $method . '" can only accept an id or code.' |
|
53 | 2 | ); |
|
54 | } |
||
55 | |||
56 | /** |
||
57 | * @deprecated |
||
58 | */ |
||
59 | public static function registerAutoloader() |
||
70 | |||
71 | 2 | public function __get($name) |
|
75 | } |
||
76 |
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.