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 |
||
33 | class JSONStorage extends PCStorage |
||
34 | { |
||
35 | |||
36 | |||
37 | /** |
||
38 | * return the name of the storage type |
||
39 | * |
||
40 | * @return string |
||
41 | */ |
||
42 | public function getName() |
||
43 | { |
||
44 | return "json"; |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * Checks if the file is writeable, readable or if the directory is. |
||
49 | * |
||
50 | * @param string $jsonFile json file that holds the pclasses |
||
51 | * |
||
52 | * @throws error |
||
53 | * @return void |
||
54 | */ |
||
55 | View Code Duplication | protected function checkURI($jsonFile) |
|
56 | { |
||
57 | //If file doesn't exist, check the directory. |
||
58 | if (!file_exists($jsonFile)) { |
||
59 | $jsonFile = dirname($jsonFile); |
||
60 | } |
||
61 | |||
62 | if (!is_writable($jsonFile)) { |
||
63 | throw new Klarna_FileNotWritableException($jsonFile); |
||
64 | } |
||
65 | |||
66 | if (!is_readable($jsonFile)) { |
||
67 | throw new Klarna_FileNotReadableException($jsonFile); |
||
68 | } |
||
69 | } |
||
70 | |||
71 | /** |
||
72 | * Clear the pclasses |
||
73 | * |
||
74 | * @param string $uri uri to file to clear |
||
75 | * |
||
76 | * @throws KlarnaException |
||
77 | * @return void |
||
78 | */ |
||
79 | public function clear($uri) |
||
80 | { |
||
81 | $this->checkURI($uri); |
||
82 | unset($this->pclasses); |
||
83 | if (file_exists($uri)) { |
||
84 | unlink($uri); |
||
85 | } |
||
86 | } |
||
87 | |||
88 | /** |
||
89 | * Load pclasses from file |
||
90 | * |
||
91 | * @param string $uri uri to file to load |
||
92 | * |
||
93 | * @throws KlarnaException |
||
94 | * @return void |
||
95 | */ |
||
96 | public function load($uri) |
||
118 | |||
119 | /** |
||
120 | * Save pclasses to file |
||
121 | * |
||
122 | * @param string $uri uri to file to save |
||
123 | * |
||
124 | * @throws KlarnaException |
||
125 | * @return void |
||
126 | */ |
||
127 | public function save($uri) |
||
150 | } |
||
151 |
The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.
The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.
To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.