Java Reference
In-Depth Information
Passing code/behavior
It's worth pausing for a moment for a small celebration. This code is much more flexible than
our first attempt, while at the same time it's easy to read and to use! You can now create
different ApplePredicate objects and pass them to the filterApples method. Free flexibility! For
example, if the farmer asks you to find all red apples that are heavier than 150 g, all you need to
do is create a class that implements the ApplePredicate accordingly. Your code is now flexible
enough for any change of requirements involving the attributes of Apple:
public class AppleRedAndHeavyPredicate implements ApplePredicate{
public boolean test(Apple apple){
return "red".equals(apple.getColor())
&& apple.getWeight() > 150;
}
}
List<Apple> redAndHeavyApples =
filter(inventory, new AppleRedAndHeavyPredicate());
You've achieved something really cool: the behavior of the filterApples method depends on the
code you pass to it via the ApplePredicate object. In other words, you've parameterized the
behavior of the filterApples method!
Note that in the previous example, the only code that really matters is the implementation of the
test method, as illustrated in figure 2.2 ; this is what defines the new behaviors for the
filterApples method. Unfortunately, because the filterApples method can only take objects, you
have to wrap that code inside an ApplePredicate object. What you're doing is similar to “passing
code” inline, because you're passing a boolean expression through an object that implements the
test method. You'll see in section 2.3 (and in more detail in chapter 3 ) that by using lambdas,
you'll be able to directly pass the expression "red".equals(apple.getColor()) && apple.getWeight()
> 150 to the filterApples method without having to define multiple ApplePredicate classes and
thus removing unnecessary verbosity.
 
Search WWH ::




Custom Search