<julien.robins...@gmail.com> wrote in message
news:1183462807.077446.322050@w5g2000hsg.googlegroups.com...
I used switch statements much more in C++ than now in Java. Mainly
because, whereas Java has introduced a discrepancy between == and
equals(), switch only applies to ==.
What I would suggest is a new switch, so that we have "switch" and
"switch-equals"
switch: runs through all cases comparing with the operator "==". May
accept null, and probably useless for strings.
"switch (x) {case y:..." should be exactly the same behavior as "if (x
== y)..."
(I *think* that's the one we have... just goes to show how much I use
it!)
Yes, I think that's an accurate mental model of how the switch
statement works
switch-equals:
uses "equals()" to test each case. Requires passing an object (or uses
auto-boxing?).
It could not accept null pointers, even though I would favor:
"switch (x) {case y:" should be exactly the same behavior as
"y.equals(x)"
so that x may be null
If ever some y is null, throw NullPointerException of course. :-)
and if x is null, of course it switches to default.
How about adding a new case statement for nulls, and leaving default
to their original semantics?
switchequals (x) {
case y:
doThis();
break;
case z:
doThat();
break;
null:
doSomethingElse();
break;
default:
giveUp();
break;
}
is syntatic sugar for:
if (null == x) {
doSomethingElse();
} else if (y.equals(x)) {
doThis();
} else if (z.equals(x)) {
doThat();
} else {
giveUp();
}
and
switchequals (x) {
case y:
doThis();
break;
case z:
doThat();
break;
default:
giveUp();
break;
}
is syntatic sugar for:
if (null == x) {
giveUp();
} else if (y.equals(x)) {
doThis();
} else if (z.equals(x)) {
doThat();
} else {
giveUp();
}
Note that the compiler was smart enough to do whatever was necessary to
avoid NullPointerException.
While we're at it, how about changing the switch statement so that
statements after a case-label MUST end in either "break;" or
"fallthrough;" (or "continue;", if you want to avoid creating a new
keyword). So the following would no longer be legal code:
switch(x) {
case 1: //fallthrough
case 2:
doSomething();
}
and instead would need to be written:
switch(x) {
case 1:
continue;
case 2:
doSomething;
break;
}
Problem is: what if there's y1 and y2 and both are equal? Simply
precise that only the first match will be acted upon.
Agreed, as I think this parallels how switch currently works.
This may be ugly, but I agree that:
* switch, as is it, is not very consistent with Java thinking, because
of the "equals" method
Note that switch statements refuse to work on anything except integers
(maybe longs?) and enums. Specifically, they don't work on objects, so the
"equals" method doesn't even come up as an issue yet.
- Oliver