Java Reference
In-Depth Information
Chapter 2. Passing code with behavior
parameterization
This chapter covers
Coping with changing requirements
Behavior parameterization
Anonymous classes
Preview of lambda expressions
Real-world examples: Comparator , Runnable , and GUI
A well-known problem in software engineering is that no matter what you do, user requirements
will change. For example, imagine an application to help a farmer understand his inventory. The
farmer might want a functionality to find all green apples in his inventory. But the next day he
might tell you, “Actually I also want to find all apples heavier than 150 g.” Two days later, the
farmer comes back and adds, “It would be really nice if I could find all apples that are green and
heavier than 150 g.” How can you cope with these changing requirements? Ideally you'd like to
minimize your engineering effort. In addition, similar new functionalities ought to be
straightforward to implement and maintainable in the long term.
Behavior parameterization is a software development pattern that lets you handle frequent
requirement changes. In a nutshell, it means taking a block of code and making it available
without executing it. This block of code can be called later by other parts of your programs,
which means that you can defer the execution of that block of code. For instance, you could pass
the block of code as an argument to another method that will execute it later. As a result, the
method's behavior is parameterized based on that block of code. For example, if you process a
collection, you may want to write a method that
Can do “something” for every element of a list
Can do “something else” when you finish processing the list
Can do “yet something else” if you encounter an error
This is what behavior parameterization refers to. Here's an analogy: your roommate knows
how to drive to the supermarket and back home. So you can tell him to buy a list of things such
as bread, cheese, and wine. This is equivalent to calling a method goAndBuy with a list of
products as argument. But one day you're at the office and you need him to do something he's
never done before: pick up a package from the post office. You now need to pass him a list of
 
Search WWH ::




Custom Search