Skip to content

Instantly share code, notes, and snippets.

@jawspeak
Created July 1, 2010 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jawspeak/459445 to your computer and use it in GitHub Desktop.
Save jawspeak/459445 to your computer and use it in GitHub Desktop.
java google collections functional programming style
// Use functional programming idioms that google collections (now called google guava) give you.
// Given:
private static final Set<String> CLEARABLE_PATHS = Sets.newHashSet("/app/search", "/app/logout");
// Don't be iterative:
// BAD
private boolean shouldClearCookie() {
for (Iterator<String> stringIterator = CLEARABLE_PATHS.iterator(); stringIterator.hasNext();) {
String clearablePath = stringIterator.next();
if (request.getRequestURI().contains(clearablePath)){
return true;
}
}
return false;
}
// Be functional:
// GOOD (-;
// elsewhere this is defined:
public static Predicate<String> containedIn(final String subString) {
return new Predicate<String>() {
public boolean apply(String input) {
return subString.contains(input);
}
};
}
private boolean shouldClearCookie() {
return Iterables.any(CLEARABLE_PATHS, containedIn(request.getRequestURI()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment