Below is a method:
private RiskFactor calculateMotoristRiskFactor()
{
if (motorist.PointsOnLicense > 3
|| motorist.Age < 25)
return RiskFactor.HighRisk;
if (motorist.PointsOnLicense > 0)
return RiskFactor.ModerateRisk;
return RiskFactor.LowRisk;
}
I don't want those if statements.
Can I use strategy pattern to solve this? If yes then too I don't want each method in the different polymorphic class should have an If statement in it.
RiskFactor is an Enum
Any better way to make this more object oriented instead of procedural?
Well, you could have a List<Tuple<Func<Motorist, bool>, RiskFactor>
:
var filters = new List<Tuple<Func<Motorist, bool>, RiskFactor>
{
Tuple.Create(m => m.PointsOnLicense > 3, RiskFactor.HIGH_RISK),
Tuple.Create(m => m.Age < 25, RiskFactor.HIGH_RISK),
Tuple.Create(m => m.PointsOnLicense > 0, RiskFactor.MODERATE_RISK),
};
Then:
var risk = filters.Where(filter => filter.Item1(motorist))
.Select(filter => filter.Item2)
.DefaultIfEmpty(RiskFactor.LOW_RISK)
.First();
That at least makes it easy to add extra checks, and it just runs down them in order. It's a little bit fiddly - I might create a custom Filter
type rather than the Tuple
for example - but it should work...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With