Complex classes like Space 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 Space, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
12 | class Space extends SplObjectStorage |
||
13 | { |
||
14 | /** |
||
15 | * @var int |
||
16 | */ |
||
17 | protected $dimension; |
||
18 | |||
19 | public function __construct(int $dimension) |
||
27 | |||
28 | public function toArray(): array |
||
37 | |||
38 | public function newPoint(array $coordinates, $label = null): Point |
||
39 | { |
||
40 | if (count($coordinates) != $this->dimension) { |
||
41 | throw new LogicException('('.implode(',', $coordinates).') is not a point of this space'); |
||
42 | } |
||
43 | |||
44 | return new Point($coordinates, $label); |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * @param null $data |
||
49 | */ |
||
50 | public function addPoint(array $coordinates, $data = null): void |
||
54 | |||
55 | /** |
||
56 | * @param null $label |
||
57 | */ |
||
58 | public function addPointWithLabels(array $coordinates, $label = null): void |
||
62 | |||
63 | /** |
||
64 | * @param Point $point |
||
65 | * @param null $data |
||
66 | */ |
||
67 | public function attach($point, $data = null): void |
||
75 | |||
76 | public function getDimension(): int |
||
80 | |||
81 | /** |
||
82 | * @return array|bool |
||
83 | */ |
||
84 | public function getBoundaries() |
||
102 | |||
103 | public function getRandomPoint(Point $min, Point $max): Point |
||
113 | |||
114 | /** |
||
115 | * @return array|Cluster[] |
||
116 | */ |
||
117 | public function cluster(int $clustersNumber, int $initMethod = KMeans::INIT_RANDOM): array |
||
126 | |||
127 | /** |
||
128 | * @return array|Cluster[] |
||
129 | */ |
||
130 | protected function initializeClusters(int $clustersNumber, int $initMethod): array |
||
151 | |||
152 | protected function iterate($clusters): bool |
||
189 | |||
190 | protected function initializeKMPPClusters(int $clustersNumber): array |
||
220 | |||
221 | private function initializeRandomClusters(int $clustersNumber): array |
||
232 | } |
||
233 |
This check looks for
do
loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.Consider removing the loop.