消除Ifs

时间:2013-07-05 09:10:55

标签: c# coding-style refactoring

我想在我的应用程序中消除ifs,但是我碰到了一堵砖墙。这是我的代码。我面临的问题是我采用了使用字典进行切换的想法,但是,在这种情况下,ifs依赖于2个不同的变量,加权和蜜蜂(这些我不能合并成一个变量)。原来它是

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

所以我把它改成了以下,这消除了ifs,但感觉不对。我知道字典适用于if在单个变量上的情况,但我觉得如果有2个或更多变量,必须有一种方法可以使用它。关于如何以干净的方式消除ifs的任何想法。这是'模式'的链接

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();
    }
}

1 个答案:

答案 0 :(得分:2)

这里不需要字典...只需使用已有的条件运算符,但在return语句中。我个人喜欢以下格式化方式。

return weighted ? WeightedCalculator
     : bee ? BeeCalculator
     : DefaultCalculator;

您可以在最终默认值之前添加任意数量的: condition ? result行。

相关问题