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:
function getName(Color $color) {
switch($color) {
case Color::RED:
return 'Red';
case Color::BLUE:
return 'Blue';
}
}But if you add another function, then make a factory class which returns an instance.
function getRGB(Color $color) {
switch($color) {
case Color::RED:
return '#FF0000';
case Color::BLUE:
return '#0000FF';
}
}Do this instead:
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 updated
Was this helpful?