sawe
sawe

Reputation: 1151

Eliminating Ifs

I would like to eliminate ifs in my application, but i have hit a brick wall. Here is my code. The problem i am facing is that i bought into the idea of using a dictionary to do the switching, however, in this case, the ifs depend on 2 different variables, weighted and bee(these i cannot combine into one variable). so originally it was

if(weighted)
    return WeightedCalculator;
else if (bee)
    return BeeCalculator;
else
    return DefaultCalculator;

So i have changed it to the following, which eliminates the ifs, but feels wrong. i do know that the dictionary is meant for cases where the if is on a single variable, but i feel there must be a way of using it if there are 2 or more variables. Any ideas as to how i could eliminate the ifs in a clean way. here is the link to this 'pattern'

http://joelabrahamsson.com/invoking-methods-based-on-a-parameter-without-if-else-statements-in-c/

public class CalculateDayCountFractionFactory : ICalculateDayCountFractionFactory
{
    private static readonly Dictionary<string, Func<ICalculateDayCount>> _dayCountCalculators = new Dictionary<string, Func<ICalculateDayCount>>
                                                                                                    {
                                                                                                        {"weighted", new WeightedDayCountCalculator()},
                                                                                                        {"bee", new BeeDayCountCalculator()}
                                                                                                    };


    public ICalculateDayCount Create(bool weighted, bool bee)
    {
        var key = weighted
                      ? "weighted"
                      : (bee
                             ? "bee"
                             : "");


        return _dayCountCalculators.ContainsKey(key)
                   ? _dayCountCalculators[key]()
                   : DefaultDayCountCalculator();
    }
}

Upvotes: 0

Views: 414

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

You don't need a dictionary here... just use a conditional operator in the way you already have, but in a return statement. Personally I like the following way of formatting it.

return weighted ? WeightedCalculator
     : bee ? BeeCalculator
     : DefaultCalculator;

You can add as many : condition ? result lines as you like before the final default value.

Upvotes: 2

Related Questions