Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we replace if statement with an object in C#

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?

like image 862
Vicky Avatar asked Jul 28 '11 19:07

Vicky


1 Answers

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...

like image 184
Jon Skeet Avatar answered Nov 07 '22 10:11

Jon Skeet