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 |
||
9 | class Base64 |
||
10 | { |
||
11 | /** |
||
12 | * Encode a string using base64url variant. |
||
13 | * |
||
14 | * @link https://en.wikipedia.org/wiki/Base64#URL_applications |
||
15 | * @param string $data |
||
16 | * @return string |
||
17 | */ |
||
18 | 164 | public static function urlEncode($data) { |
|
21 | |||
22 | /** |
||
23 | * Decode a string using base64url variant. |
||
24 | * |
||
25 | * @link https://en.wikipedia.org/wiki/Base64#URL_applications |
||
26 | * @param string $data |
||
27 | * @throws \UnexpectedValueException |
||
28 | * @return string |
||
29 | */ |
||
30 | 130 | public static function urlDecode($data) { |
|
46 | |||
47 | /** |
||
48 | * Check whether string is validly base64url encoded. |
||
49 | * |
||
50 | * @link https://en.wikipedia.org/wiki/Base64#URL_applications |
||
51 | * @param string $data |
||
52 | * @return bool |
||
53 | */ |
||
54 | 112 | public static function isValidURLEncoding($data) { |
|
57 | |||
58 | /** |
||
59 | * Encode a string in base64. |
||
60 | * |
||
61 | * @link https://tools.ietf.org/html/rfc4648#section-4 |
||
62 | * @param string $data |
||
63 | * @throws \RuntimeException If encoding fails |
||
64 | * @return string |
||
65 | */ |
||
66 | 167 | View Code Duplication | public static function encode($data) { |
75 | |||
76 | /** |
||
77 | * Decode a string from base64 encoding. |
||
78 | * |
||
79 | * @link https://tools.ietf.org/html/rfc4648#section-4 |
||
80 | * @param string $data |
||
81 | * @throws \RuntimeException If decoding fails |
||
82 | * @return string |
||
83 | */ |
||
84 | 131 | public static function decode($data) { |
|
93 | |||
94 | /** |
||
95 | * Check whether string is validly base64 encoded. |
||
96 | * |
||
97 | * @link https://tools.ietf.org/html/rfc4648#section-4 |
||
98 | * @param string $data |
||
99 | * @return bool |
||
100 | */ |
||
101 | 4 | public static function isValid($data) { |
|
104 | } |
||
105 |
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.