Java Reference
In-Depth Information
instructions: go to the post office, use this reference number, talk to the manager, and pick up
the parcel. You could pass him the list of instructions by email, and when he receives it, he can
go ahead and follow the instructions. You've now done something a bit more advanced that's
equivalent to a method: go, which can take different new behaviors as arguments and execute
them.
We start the chapter by walking you through an example of how you can evolve your code to be
more flexible for changing requirements. Building on this knowledge, we show how to use
behavior parameterization for several real-world examples. For example, you may have already
used the behavior parameterization pattern using existing classes and interfaces in the Java API
to sort a List, to filter names of files, or to tell a Thread to execute a block of code or even
perform GUI event handling. You'll soon realize that using this pattern is verbose in Java at the
moment. Lambda expressions in Java 8 tackle the problem of verbosity. We show in chapter 3
how to construct lambda expressions, where to use them, and how you can make your code
more concise by adopting them.
2.1. Coping with changing requirements
Writing code that can cope with changing requirements is difficult. Let's walk through an
example that we'll gradually improve, showing some best practices for making your code more
flexible. In the context of a farm-inventory application, you have to implement a functionality to
filter green apples from a list. Sounds easy, right?
2.1.1. First attempt: filtering green apples
A first solution might be as follows:
The highlighted line shows the condition required to select green apples. But now the farmer
changes his mind and wants to also filter red apples. What can you do? A naïve solution would
be to duplicate your method, rename it as filterRedApples, and change the if condition to match
red apples. Nonetheless, this approach doesn't cope well with changes if the farmer wants
 
Search WWH ::




Custom Search