Last updated on 2012-12-11
Last month I discovered Google’s Guava library, a really useful set of utility classes for everyday java programming. One of these classes, better yet, one concept that I have grown to love are Predicates.
A Predicate is a very simple interface that determines truth or falsehood for a given input. Just that. So what is so good about this interface?. I’ll show you with an example, taken directly from my code. Let’s say that I have a list with all the procedural links connected to a process, and I wanted to filter the list for conditional links. This is the typical way to do this:
List instrumentLinks = new ArrayList(); for(OPMProceduralLink link : allProceduralLinks) { switch(link.getKind()) { case CONSUMPTION_CONDITION: case EFFECT_CONDITION: case INSTRUMENT_CONDITION: instrumentLinks.add(link); } }
There is nothing wrong with this code. It’s just that it doesn’t show intention. Most programmers will understand what I wanted to achieve after reading the lines, because they understand how I achieved it.
This is where Predicates come to the rescue. First, I created a class that implements Predicate
and returns true when it is given a OPMProceduralLink
with OPMProceduralLinkKind.INSTRUMENT
:
public enum IsOPMConditionalLink implements Predicate { INSTANCE; @Override public boolean apply(final OPMProceduralLink link) { switch(link.getKind()) { case CONSUMPTION_CONDITION: case EFFECT_CONDITION: case INSTRUMENT_CONDITION: return true; } return false; } }
Since the Predicate
has no state, I use an enum
for the Singleton instance. Now to filter the list I only have to write one line of code:
Collection instrumentLinks = Collections2.filter(allProceduralLinks, IsOPMConditionalLink.INSTANCE);
I think this code tells the reader a lot more, with a lot less. And makes it more understandable – one of the main goals of every good programmer.
P.S.: I know there are subtle differences, like using a Collection
instead of a list (and there is a reason why a List
is not filtered). But most of the time there is no difference.
Be First to Comment