Reference: Java 8 in Action

Behavior Parametrization

Objective - Filter out all the Apples with Green color

Attempt 1 - Simple and Straightforward:

public static void List<Apple> filterGreenApples(List<Apple> inventory) {
    List<Apple> result = new ArrayList<>();
    for(Apple apple : inventory) {
        if("green".equalsIgnoreCase(apple.getColor())){
            result.add(apple);
        }
    }
    return result;
}

But now, there is a change in requirement, and we want to filter out Green as well as Red Apples.

We can see that the above mentod is quite rigid and it does not adapt to change in requirements. A naive approach to handle this change in requirement is to write another implementation _filterRedApples(), _which will be identical to above menthod. But, this solution is also not scalable, as tomorrow, we may get a requirement to filter yellow and blue apples!

However, we can make the method more generic by update the method to accept 'color' as an additional parameter. This way, the method could work for filtering out apples of any color.

Attempt 2 - Parametrizing the color

public static void List<Apple> filterApplesByColor(List<Apple> inventory, String color) {
    List<Apple> result = new ArrayList<>();
    for(Apple apple : inventory) {
        if(apple.getColor().equalsIgnoreCase(color)){
            result.add(apple);
        }
    }
    return result;
}

and we can call the above method as:

List<Apple> greenApples = filterApplesByColor(inventory, "green");
List<Apple> redApples = filterApplesByColor(inventory, "red");

But now, the customer comes and says that he wants to classify the apples as light and heavy apples. Apples more than 150g would qualify as heavy apples. We follow our previous learning, and implement a method that accepts weight as a parameter.

public static void List<Apple> filterApplesByWeight(List<Apple> inventory, int weight) {
    List<Apple> result = new ArrayList<>();
    for(Apple apple : inventory) {
        if(apple.getWeight() > weight){
            result.add(apple);
        }
    }
    return result;
}

You would immediately notice, that we have duplicated most of the implementation in this method, like:

  1. Traversing the inventory
  2. Applying the filtering criteria on each items in the inventory

This is disappointing as it breaks the DRY principle. If we want to alter the filter traversing to enhance performance, we would have to change all the method implementations instead if a single one. This is an expensive engineering effort!

results matching ""

    No results matching ""