Java Reference
In-Depth Information
}
return result;
}
This is a good solution, but notice how you have to duplicate most of the implementation for
traversing the inventory and applying the filtering criteria on each apple. This is somewhat
disappointing because it breaks the DRY (don't repeat yourself) principle of software
engineering. What if you want to alter the filter traversing to enhance performance? You now
have to modify the implementation of all of your methods instead of a single one. This is
expensive from an engineering effort perspective.
You could combine the color and weight into one method called filter. But then you'd still need a
way to differentiate what attribute you want to filter on. You could add a flag to differentiate
between color and weight queries. (But never do this! We'll explain why shortly.)
2.1.3. Third attempt: filtering with every attribute you can think of
Our ugly attempt of merging all attributes appears as follows:
You could use it as follows (but it's really ugly):
List<Apple> greenApples = filterApples(inventory, "green", 0, true);
List<Apple> heavyApples = filterApples(inventory, "", 150, false);
...
This solution is extremely bad. First, the client code looks terrible. What do true and false mean?
In addition, this solution doesn't cope well with changing requirements. What if the farmer asks
you to filter with different attributes of an apple, for example, its size, its shape, its origin, and so
on? Furthermore, what if the farmer asks you for more complicated queries that combine
attributes, such as green apples that are also heavy? You'd either have multiple duplicated filter
methods or one giant, very complex method. So far you've parameterized the filterApples
 
Search WWH ::




Custom Search