4 ms·
Making things into enums that shouldn't be enums is a fun trap to fall into. Much of the time what you really want is a complex type so that you can communicate
by bob1029 2y ago
Making things into enums that shouldn't be enums is a fun trap to fall into. Much of the time what you really want is a complex type so that you can communicate these additional facts. In this case I'd do something like:
class Widget
{
WidgetFlavor Flavor; //Undefined, Vanilla, Chocolate, Strawberry
string? OtherFlavor;
}
This is easy to work from a consumer standpoint because if you have a deviant flavor to specify, you don't bother setting the Flavor member to anything at all. You just set OtherFlavor. Fewer moving pieces == less chance for bad times.
The first (default) member in an enum should generally be something approximating "Undefined". This also makes working with serializers and databases easier.
- ryanschaefer 2y ago> Fewer moving pieces == less chance for bad times. Is this not a case for explicitly specifying all flavors? Other flavor has essentially introduced infinite moving pieces.
- IshKebab 2y agoThis is not a good design. You've introduced representable invalid states (Flavor=Vanilla, Other flavor="DarkChocolate"). At the least you want this... enum Flavor { Chocolate, Banana, Strawberry, Other(String), } But that's not right either. What you really want is #[non_exhaustive] enum Flavor { Chocolate, Banana, Strawberry, } impl ToString for Flavor ...
- msy 2y agoUntil you get a Widget.OtherFlavor = 'Vanilla'