Java Reference
In-Depth Information
multiple colors: light green, dark red, yellow, and so on. A good principle is this: after writing
similar code, try to abstract.
2.1.2. Second attempt: parameterizing the color
What you could do is add a parameter to your method to parameterize the color and be more
flexible to such changes:
public static List<Apple> filterApplesByColor(List<Apple> inventory,
String color ) {
List<Apple> result = new ArrayList<>();
for (Apple apple: inventory){
if ( apple.getColor().equals(color) ) {
result.add(apple);
}
}
return result;
}
You can now make the farmer happy and call your method as follows:
List<Apple> greenApples = filterApplesByColor(inventory, "green");
List<Apple> redApples = filterApplesByColor(inventory, "red");
...
Too easy, right? Let's complicate the example a bit. The farmer comes back to you and says, “It
would be really cool to differentiate between light apples and heavy apples. Heavy apples
typically have a weight greater than 150 g.”
Wearing your software engineering hat, you realize in advance that the farmer may want to vary
the weight, so you create the following method to cope with various weights through an
additional parameter:
public static List<Apple> filterApplesByWeight(List<Apple> inventory,
int weight ) {
List<Apple> result = new ArrayList<>();
For (Apple apple: inventory){
if ( apple.getWeight() > weight ){
result.add(apple);
}
 
Search WWH ::




Custom Search