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:
Complex classes like Loader often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Loader, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
3 | final class Loader |
||
4 | { |
||
5 | |||
6 | private $root; |
||
7 | private $is_live; |
||
8 | private $included_files = array(); |
||
9 | |||
10 | private static $instance; |
||
11 | |||
12 | private function __construct() |
||
13 | { |
||
14 | $this->is_live = (isset($_SERVER['HTTP_HOST']) && substr($_SERVER['HTTP_HOST'], 0, 4) !== 'dev.'); |
||
15 | return $this; |
||
|
|||
16 | } |
||
17 | |||
18 | public static function instance() |
||
24 | |||
25 | private function get_root() |
||
36 | |||
37 | private function get_delimiter() |
||
41 | |||
42 | private function check_delimiters($path) |
||
46 | |||
47 | private static function get_class_name($path) |
||
52 | |||
53 | private static function get_extension($type) |
||
71 | |||
72 | View Code Duplication | public static function getImagePath($type, $file) |
|
83 | |||
84 | View Code Duplication | private static function get_path($type, $file) |
|
94 | |||
95 | private function get_included_files() |
||
99 | |||
100 | private function add_included_file($path) |
||
104 | |||
105 | public static function load($type, $files, $data = array()) |
||
132 | |||
133 | private static function create_reflection_class($file) |
||
138 | |||
139 | public static function loadInstance($type, $file) |
||
153 | |||
154 | public static function loadNew($type, $file, $data = array()) |
||
165 | |||
166 | public static function getRoot() |
||
170 | |||
171 | public static function isLive() |
||
175 | |||
176 | public static function getRootURL($site = '') |
||
188 | |||
189 | } |
||
190 |