matt rtfm commons collections has closures

Published:
TRIGGER WARNING: This post contains content that no longer represents me.

I have a really convoluted and confusing story. My friends that know it (including my wife) still don’t believe it sometimes, but it’s true.

I was once an evangelical Christian, a Southern Baptist, an adult Sunday School teacher, and a door-to-door evangelist. I not only voted Republican and/or Libertarian in multiple elections, I volunteered during Bob Dole’s 1996 election campaign.

Reading what I just typed, it’s honestly hard to believe it myself.

One day I plan to tell this story in written form, but that day is not today. Rather than erase that past completely, I’ve preserved it in a limited form as a part of this site’s permanent historical archive. It’s important to demonstrate that we can all grow.

Welcome to the dim corner of the library, where fools rush in and angels fear to tread!

This blog post is ancient. If it is technical, the information is likely inaccurate, or at least out of date. If it is non-technical, it’s entirely possible that the relevant facts and my own opinions have changed significantly since it was written.

It is only preserved as part of this site’s permanent historical archive.

Thanks to everyone who pointed me to Commons Collections and its Functor package yesterday. To me, this is just one step below having closures natively present in the language. FYI, I was able to remove all duplication from my class and reduce the LOC from 211 to 136 - in other words, 75 lines of useless code GONE.

Here is what I did. First, I defined Predicates for each of my conditions. The simplest ones called a boolean method on the User object:

private final Predicate isX = new Predicate() {<br></br>  public boolean evaluate(Object object) {<br></br>     return ((User) object).isX();<br></br>  }<br></br>}<br></br>

Only slightly more complicated ones checked to see if a given Collection was empty on the User object:

private final Predicate isX = new Predicate() {<br></br>  public boolean evaluate(Object object) {<br></br>     return CollectionUtils.isNotEmpty(((User) object).getItems());<br></br>  }<br></br>}<br></br>

Next, I defined a method that would check the delegations for the User to see if any of them were an X:

boolean checkDelegations(User user, Predicate checkPredicate) {<br></br>  return CollectionUtils.exists(user.getDelegations(), checkPredicate);<br></br>}<br></br>

Finally, I implemented the security methods:

public boolean canDoThis() {<br></br>  return isX.evaluate(loggedInUser) || checkDelegations(loggedInUser, isX);<br></br>}<br></br>

Maybe it isn’t the most elegant or simplest of solutions, but it sure is a lot better than what I posted yesterday!

P.S. Since this is a Christian blog, I must remind you that RTFM stands for Read The FINE Manual!