Be careful of enum in switch statements
If an enum is in more than one switch statement. Consider making a factory class which returns singleton class for the enum value.
For example, if you only have one instance of this, its ok:
1
function getName(Color $color) {
2
switch($color) {
3
case Color::RED:
4
return 'Red';
5
6
case Color::BLUE:
7
return 'Blue';
8
}
9
}
Copied!
But if you add another function, then make a factory class which returns an instance.
1
function getRGB(Color $color) {
2
switch($color) {
3
case Color::RED:
4
return '#FF0000';
5
6
case Color::BLUE:
7
return '#0000FF';
8
}
9
}
Copied!
Do this instead:
1
class ColorFactory {
2
public static function get(ColorEnum $color) {
3
switch ($color) {
4
case ColorEnum::RED:
5
return ColorRed::get();
6
7
case ColorEnum::Blue:
8
return ColorBlue::get();
9
}
10
}
11
}
12
13
class Color extends Color {
14
public function get(ColorEnum $color) {
15
switch ($color) {
16
case ColorEnum::RED:
17
return ColorRed::get();
18
19
case ColorEnum::Blue:
20
return ColorBlue::get();
21
}
22
}
23
}
24
25
abstract class ColorBase extends Color {
26
public function getName(): string;
27
public function getRGB(): string;
28
}
29
30
final class ColorRed extends Color {
31
public function getID(): Color {
32
return Color::RED;
33
}
34
35
public function getName(): string {
36
return 'Red';
37
}
38
39
public function getRGB(): string {
40
return '#FF0000';
41
}
42
}
43
44
final class ColorBlue extends Color {
45
public function getID(): Color {
46
return Color::Blue;
47
}
48
49
public function getName(): string {
50
return 'Blue';
51
}
52
53
public function getRGB(): string {
54
return '#0000FF';
55
}
56
}
57
58
function main() {
59
$color = ColorFactory::get($color)
60
return $color->getName();
61
}
Copied!
Yes there is more code, but its easier to manage the code. When adding a new Enum you are not required to remember which files to update, the compiler will catch any undefined functions.
Last modified 1yr ago
Copy link