Re: switch using strings
This message is in MIME format. The first part should be readable text,
while the remaining parts are likely unreadable without MIME-aware tools.
--232016332-1380946009-1298487257=:5333
Content-Type: TEXT/PLAIN; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8BIT
On Tue, 22 Feb 2011, Arne Vajh?j wrote:
On 21-02-2011 11:44, Lew wrote:
rossum wrote:
Or use a multiple-exit method:
int String2MessageIndex(String messName) {
if (messName.equals("This")) { return 0; }
if (messName.equals("That")) { return 1; }
if (messName.equals("The other")) { return 2; }
if (messName.equals("Something")) { return 3; }
if (messName.equals("Different")) { return 4; }
// As many more as needed ...
// Default return value.
return UNRECOGNIZED_MESSAGE;
}
Throwing an exception would be an alternative for an unrecognized
message.
That's just another form of the 'if' chain.
Personally I'd still use 'else if' even with the 'return' statements.
switch with N cases and default seems to be most accurate translated to
1 if, N-1 else if and 1 if.
^^
That if should be an else, i assume.
A colleague suggested today that it would be useful to be able to switch
on classes, a sort of switch-instanceof hybrid. Something like:
Object value;
switch (value.getClass()) {
case String: storeString((String)value); break;
case Double: storeNumber((Double)value); break;
// etc
}
This would usually be something which would be better handled by
polymorphism, but there are times when you can't do that. There would be a
definite risk that introducing it would lure people away from
polymorphism.
It would be particularly nice if the compiler (or IDE, or PMD/FindBugs)
was able to give you a warning when you were missing a case for a possible
subclass. So for:
Payment p;
switch (pg.getClass()) {
case CreditCard: authorizeCreditCard((CreditCard)p); break;
case GiftVoucher: redeemGiftVoucher((GiftVoucher)p); break;
}
It could warn you that you'd forgotten about paying with loyalty points.
While we're on the subject of reforming switch, i'd like to see the back
of fall-through and break. I want switches to look like:
switch(i) {
case 1: doSomething();
case 2: {
doSomething();
doSomethingElse();
}
case 3, 4: doSomeOtherThing();
}
I already use a braces-and-break style:
switch(i) {
case 1: {
doSomething();
} break;
case 2: {
doSomething();
doSomethingElse();
} break;
case 3:
case 4: {
doSomeOtherThing();
}
}
But it's clunky. I don't know how to introduce the reformed syntax in a
backwards-compatible way, though.
tom
--
What? Yeah!
--232016332-1380946009-1298487257=:5333--