While reading through some ai-generated code today, I was caught off guard when I saw a switch statement inside of a boolean. What on earth has ai done now, I wondered. Here is the suspect:
public boolean canChangeTo(OrderStatus newStatus) {
switch (this) {
case PLACED:
return newStatus == PROCESSING || newStatus == CANCELLED;
case PROCESSING:
return newStatus == SHIPPED || newStatus == CANCELLED;
case SHIPPED:
return newStatus == DELIVERED;
default:
return false;
}
}
Shortly after marveling at "ooo, this is a thing?" I started to question it. Why does this feel different?
Basically in every other case besides enum, this is bad. Enum, to my knowledge, is the only case where this is acceptable. Why? Because in a flow where there can be one and only one direction, like order processing, this checks out. Each one will hit in the order it is intended to hit. Each case will be found true at the right time in the process, and will update the status accordingly.
We can define our fixed, or set values (enums, short for enumeration) to use later in our switch.
That might look like:
public enum OrderStatus {
PLACED("Placed"),
PROCESSING("Processing"),
SHIPPED("Shipped"),
DELIVERED("Delivered"),
CANCELLED("Cancelled");
}
We use enums when we have a distinct list of choices that do not change. This could also work for days of the week or the current states of your most recent job applications. Because we are using enum, we avoid typos. Also, using your choices as enum values makes them classes in Java - a whole 'nother level of excitement.
But back to my boolean-switch...
Upon doing further digger I discovered that what claude had spat out (no hate on claude, I love claude!) was actually not optimized. There is a better way to write the boolean-switch. Since Java 14, we can use arrows to slim down our writing.
public boolean canChangeTo(OrderStatus newStatus) {
return switch (this) {
case PLACED -> newStatus == PROCESSING || newStatus == CANCELLED;
case PROCESSING -> newStatus == SHIPPED || newStatus == CANCELLED;
case SHIPPED -> newStatus == DELIVERED;
default -> false;
};
}
...slimmer and concise! My brain likes this better.
A peculiar boolean-switch has made me realize that using enums is incredibly more powerful and efficient than writing a string in an if-else statement. By using the this keyword on the switch statement itself, it evaluates the enum value and not the boolean value. If you want to "switch" on the boolean, then just use an if else statement, because there is only two values anyways...
I used to lean into if-else statements, but the switch is starting to grow on me.
Top comments (0)