2 ms·
It has been a while since I wrote Java, but if my memory is correct, Java has a much cleaner solution to this. In Java an enum is just a class with a fixed numb
by kerkeslager 12y ago
It has been a while since I wrote Java, but if my memory is correct, Java has a much cleaner solution to this. In Java an enum is just a class with a fixed number of instances, each with a constant name. You can make the instances private and expose all of your behavior through the interface of the class, using a "factory" method to find the correct instance (I say factory in quotes because it doesn't create the instance, it just finds the correct instance, which already exists). There's nothing stopping you from doing a switch-case against the instances, but at least if someone does that it will be limited to the enum class. And with some discipline you can define all the properties in the enum's constructor so no switch-cases are necessary. This mitigates all the OP's concerns, I think.
In C# you can use extension methods to keep all your switch-cases in one place, but it takes a little more work to enforce this with private visibility. I haven't thought through this completely, but my first attempt might be to replace the enum with a class with a private constructor and expose public static const instances, or maybe even hide the instances behind a factory method. I haven't tried this in practice, however, so I'm not sure what the implications of that approach are.