“Imperative code should be your default, your first choice as of Java 7”

Let’s say you’re not at Java 8 yet, you’re still learning how to spell l-a-m-b-d-a (see? I did it), and yet you still want to get into this functional programming “thing.” But let’s also stipulate that you know and love Guava.

Even though the Guava team cautions that “functional programming in Java can only be approximated through awkward and verbose use of anonymous classes,” you know that the Guava folks have also tempted and taunted you by creating a number of classes and interfaces that look an awful lot like Java 8’s new functional interfaces (see, e.g., Predicate and Function). Resistance is futile, you remind yourself.

So you create something like this:

[code lang=”java”]
public void whatever() {
class Student {
final String firstName;
final String lastName;
public Student(String firstName, String lastName) {
this.firstName=firstName;
this.lastName=lastName;
}
}
ImmutableSet<Student> students = ImmutableSet.of(
new Student("James", "Jones"),
new Student("Neil", "Sanders"),
new Student("Michael", "Rice"),
new Student("Michael", "Shore"));
Iterable<Student> michaels = Iterables.filter(students, new Predicate<Student>() {
@Override public boolean apply(Student input) {
return StringUtils.equalsIgnoreCase(input.firstName, "michael");
}
});
for (Student michael : michaels) {
System.out.println(michael.lastName);
}
}
[/code]

Looks kind of slick and kind of functional, huh? Looks like it gets you a few steps closer to Java 8, right? But then you’ve got a comment something like the following from the Guava team: why don’t you just loop through them? That’s easier to read, isn’t it? They say the following is more virtuous (at least for Java 7 and older) — largely because it takes fewer lines of code and because it’s more readable:

[code lang=”java”]
// …
Set<Student> michaels = new HashSet<Student>();
for (Student candidate : students) {
if (StringUtils.equalsIgnoreCase(candidate.lastName, "rice"))
michaels.add(candidate);
}
// …
[/code]

In fact, the Guava folks go so far as to say:

Please be sure, when using Guava’s functional utilities, that the traditional imperative way of doing things isn’t more readable. Try writing it out. Was that so bad? Was that more readable than the preposterously awkward functional approach you were about to try?

The Guava folks are really thoughtful about the code, so I have no issue with their comment except that they’ve missed an important psychological component. They missed the fact that it’s so much fun.

Leave a Reply

Your email address will not be published. Required fields are marked *