gotta vent. it would make life so much easier if i could use a string to determine which case to call. i'm sure there is a good reason why ya can't (which is probably beyond me), but what is that reason?
If you look at the JVM Spec, there's an instruction called tableswitch which is how switch statements typically get implemented. It's a fast way of getting to a particular spot in your code based on the switch value, without doing a lot of comparisons. (It also takes more memory than multiple comparisons would, but that's usually considered a fair trade.) This mechanism works pretty well as long as you want to switch on some sort of integer value - at least, one in a reasonable range. Longs are not allowed in switch statements, because they would require too much memory to implement simply with tableswitch. Strings and other objects would be more complex, much less amenable to treating with tableswitch. I suppose you could use a tableswitch as part of a hashtable implementation which would look up the correct jump point. But Gosling and company chose to keep the JVM and compiler requirements relatively simple in this area. Restricting the types of inputs allowed in switch() means you end up using tableswitch for those situations it works well in, and you're forced to find alternatives where it wouldn't work as well. I do think a switch statement looks better than a long series of if / else if statements, and it would be nice to have this option. I wonder how it's implemented in C# for objects? Something hashtable-based I'm guessing. I'll have to take a look at that. But generally, using if / else if works fairly well most of the time, and there are often other OO-type alternatives if this is unsatisfactory.
Originally posted by Jim Yingst: there are often other OO-type alternatives if this is unsatisfactory.
For example a Map mapping String's to instances of a Strategy.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus