Reputation: 1868
I'm trying to transform a simple if-else statement that I've found myself using all over the place to a more elegant lambda expression. But I'm having a hard time coming up with a solution from what I've been reading.
The simple statement goes like:
if (status.getStatus() == 'A') then
handleA();
else if (status.getStatus() == 'B') then
handleB();
else
handleEverythingElse();
I know I could use the Command pattern with a map, but I'm sure there's some Java 8 elegance that I'm missing. Could someone show me the interface & impl, as well as it's usage in the body of the code (I learn by example)?
Any help would be much appreciated!
Upvotes: 0
Views: 563
Reputation: 1868
Maybe I hadn't fully explained my problem, but my colleague proposed another solution that I really like. He suggested I make the if-else block a java.util.Supplier, and invoke it in the Entity class where I need it.
So my code went from this block of logic sprinkled everywhere:
public class ServiceImpl {
...
if (entity.getStatus) == 'A' then
finalStatus = handleA();
else if (entity.getStatus() == 'B') then
finalStatus = handleB();
else
finalStatus = handleEverythingElse();
...
}
To this nicely compacted form:
public class ServiceImpl {
finalStatus = entity.getFinalStatus(this::handleStatus);
public int handleStatus() {
return dao.getStatus();
}
}
With the implementation in my Entity class:
public class Entity {
public int handleStatus(Supplier<Integer> s) {
int finalStatus;
if (status) == 'A' then
finalStatus = handleA();
else if (status() == 'B') then
finalStatus = handleB();
else
finalStatus = supplier.get();
return status;
}
}
I hope this make sense...
Upvotes: 0
Reputation: 140457
If/else or even switch are not the "good OO design" answer. Neither are lambdas. Retrieving the status from somewhere, to make then a decision based on that - that is procedural programming; not OO.
You see, what you actually have in front of you - is a state machine. You have different states; and the point is: if your "thing" is in state A; then you want to do something ( invoke handleA() ). If your are in state B; you want to do something too ( like invoke handleB() ).
So, what you actually have is:
abstract class State {
abstract void doIt();
...
StateA extends State {
@Override
void doIt() { handleA(); }
So, from the client side, you just call doIt() on same object of class State.
Thus: if you are really interested in improving your code base, learn how to use polymorphism to get rid of your if/else/switch statements.
You can watch this video to get an idea what I am talking about.
Upvotes: 2