I have the following method:
Float getPriceEqualsCategoryName(BrowseNode node, Float productPrice) {
String name = node.getName();
for (Entry<String, List<RangeValue>> entry : categoryToFee.entrySet()) {
if (name.equals(entry.getKey())) {
List<RangeValue> values = entry.getValue();
for (RangeValue value : values) {
if (productPrice < value.getMinValue())
return value.getMinValue();
if (value.getRange().contains(productPrice))
return value.getReferPercentFee() / 100 * productPrice;
}
}
}
if (node.getAncestors() == null)
return 0f;
return getPriceEqualsCategoryName(node.getAncestors().getBrowseNode().get(0), productPrice);
}
In the above method I have to loop over something similar to tree structure bottom up and check if the name of the node EQUALS to entry name in the map. if yes - I will calculate the price according to it.
As a second choice, I need to loop again to check if the name CONTAINS the entry name in the map.
I wrote a similar method:
Float getPriceContainsCategoryName(BrowseNode node, Float productPrice) {
String name = node.getName();
for (Entry<String, List<RangeValue>> entry : categoryToFee.entrySet()) {
if (name.contains(entry.getKey())) {
List<RangeValue> values = entry.getValue();
for (RangeValue value : values) {
if (productPrice < value.getMinValue())
return value.getMinValue();
if (value.getRange().contains(productPrice))
return value.getReferPercentFee() / 100 * productPrice;
}
}
}
if (node.getAncestors() == null)
return 0f;
return getPriceContainsCategoryName(node.getAncestors().getBrowseNode().get(0), productPrice);
}
As you see, the only difference is the name.equals vs name.contains in the 4th line.
I don't like this duplicated code.. is there a better way to write it?