Hacker News new | ask | show | jobs
by masklinn 1673 days ago
> - "Often you find the same switch statement scattered about a program in different places. If you add a new clause to the switch, you have to find all these switch, statements and change them. The object-oriented notion of polymorphism gives you an elegant way to deal with this problem." -- fair enough

Even that seems like it could easily be way overkill e.g. if you have multiple switches which, say, generate a label from an enum, the first step is probably to add a utility function / method, not to migrate the whole thing over to polymorphism.

Although there is one thing to be said about context:

* OP works in C#, whose enums are literally useless (they’re like C’s)

* apparently even in Java (which at least has type-safe enums even if not sum types), `switch` is unable to check for completeness

3 comments

Generally the issue with the switches scattered about (or more generally, and concern about conditions scattered about the codebase) is that the body of each case is different. Of course if all the bodies are the same the easier option is a utility method.
Switch statements are not required to be exhaustive, but switch expressions are. I’d have to check but I think it was found that changing the exhaustiveness requirement would break too much source code. The compiler will still insert some some sort of default case because somebody might add to the enumerator, and it might be in a separate compilation unit.
As someone who works in C# and finds enums useful, I'd be curious to know why you describe them as literally useless.
A C# enum is, like a C enum (as they were explicitly introduced to be compatible with those), just a bunch of constants for integers.

So when you have an enum-typed value, odds are good that it’s one of the named ones but there’s no mechanism anywhere preventing it to be any other integer of the underlying type.

But how is that an issue? I guess when you are casting random integer to the enum-type without any checks?
> But how is that an issue? I guess when you are casting random integer to the enum-type without any checks?

Any caller can send any garbage (if you're publishing a package / API), likewise a dependency can return any garbage, etc... C#'s enums are entirely indicative.

Then you have the default path, throwing an exception. I don’t see how that is different from accessing an array with an OOB index.