Re: Enum, switch, and a null
On Aug 27, 3:56 pm, Wojtek <nowh...@a.com> wrote:
Given the following (bunch of stuff missing for clarity):
---------------------------------------
enum Foo
{
ONE, TWO;
}
...
switch(getFoo())
{
default:
ONE:
doOne();
break;
TWO:
doTwo();
break;}
---------------------------------------
If getFoo() returns a null, then an exception occurs.
Should not the default case be processed? It should be the equivalent
of a "not found" value, I would think.
--
Wojtek :-)
<SSCCE id="broken" pattern="switchOnTypeToken">
public class TestEnums {
enum Test{
ONE, TWO
}
public static void main(String[] args) {
switch (getFoo()) {
case ONE:
System.out.println("One");
break;
case TWO:
System.out.println("Not one");
break;
default:
System.out.println("Other");
}
}
private static Test getFoo() {
return null;
}
}
</SSCCE>
Wow!
I would have expected the same thing as you did.
Although, Switch is usually an antipattern. You should consider
adding a value to your enum type for Other, and also adding methods to
your enum to replace switch branches.
<example id="fixed" pattern="polymorphicStrategyOrState" fixes-
SSCCE="broken">
public class TestEnums {
enum Test{
ONE {
public void doFoo() {
System.out.println("One");
}
}
,
TWO {
public void doFoo() {
System.out.println("Not one");
}
},
UNDECIDED {
public void doFoo() {
System.out.println("Other");
}
};
public abstract void doFoo();
}
public static void main(String[] args) {
getFoo().doFoo();
}
private static Test getFoo() {
return Test.UNDECIDED;
}
}
</example>