I’d like some advice on refactoring the following method:
public boolean makeDecision(String group, int level, int primaryAmount, int secondaryAmount)
{
if (group.equals("A"))
{
switch (level)
{
case 0 : return primaryAmount > 10000;break;
case 1 : return primaryAmount > 20000;break;
default : return secondaryAmount > 30000; break;
}
}
else if (group.equals("B"))
{
switch (level)
{
case 0 : return primaryAmount > 40000;break;
case 1 : return primaryAmount > 50000;break;
default : return secondaryAmount > 60000; break;
}
}
else if (group.equals("C"))
{
switch(level)
{
case 0 : return primaryAmount > 70000;break;
case 1 : return primaryAmount > 80000;break;
default : return secondaryAmount > 90000; break;
}
}
return false;
}
What I’d like to achieve:
- Allow the code to follow the open/closed principle as there will be more groups / levels in time.
- Remove the duplication in the ‘level’ switch statement.
- Ideally remove the ‘group’ top level switch statement.
Groups look like they have behaviour. You could promote the string group to a first class type. You can also put methods on the class to represent the logic you have got. I’ve put daft names on the variables, they could do with much better ones.
So now you can reduce your top level statement down to
You may wish to consider using the null object pattern to handle an unknown group.
If you say that the levels will grow in time, then I would consider doing almost exactly the same again to introduce the
Levelclass and push the if/else chain in there as another layer of polymorpshim. This would then become the double dispatch pattern as first you’d dispatch on the type ofGroupand then on the type ofLevel. This should mean that you can add new code without needing to modify the existing ones.