如何重构如此大的IF-ELSE声明

时间:2016-07-06 10:12:03

标签: c# refactoring

我有一个很大的if-else声明。我怎么能重构它?任何人都可以举一些例子来说明它更漂亮吗?谢谢!

public enum FireState
{
    None,
    NoneToMinor,
    Minor,
    MinorToNone,
    MinorRecovery,
    MinorToMajor,
    Major,
    MajorToNone,
    MajorRecovery
}

private static FireState GetFireState(int previousRespinCount, int currentRespinCount, bool isRecovery)
{
    FireState fire = FireState.None;

    if ((isRecovery || previousRespinCount == 0) && currentRespinCount < MinorJackpotMinRange)
    {
        fire = FireState.None;
    }
    else if (previousRespinCount == 0 &&
        (currentRespinCount >= MinorJackpotMinRange
        && currentRespinCount < MinorJackpotMaxRange))
    {
        fire = FireState.MinorRecovery;
    }
    else if (isRecovery && currentRespinCount >= MinorJackpotMaxRange)
    {
        fire = FireState.MajorRecovery;
    }
    else if (previousRespinCount == (MinorJackpotMinRange - 1)
        && currentRespinCount == MinorJackpotMinRange)
    {
        fire = FireState.NoneToMinor;
    }
    else if (previousRespinCount >= MinorJackpotMinRange
        && (currentRespinCount > 0 && currentRespinCount < MinorJackpotMaxRange))
    {
        fire = FireState.Minor;
    }
    else if ((previousRespinCount >= MinorJackpotMinRange &&
        previousRespinCount < MinorJackpotMaxRange) &&
        currentRespinCount == 0)
    {
        fire = FireState.MinorToNone;
    }
    else if (previousRespinCount == (MinorJackpotMaxRange - 1)
        && currentRespinCount == MinorJackpotMaxRange)
    {
        fire = FireState.MinorToMajor;
    }
    else if (previousRespinCount >= MinorJackpotMaxRange &&
        currentRespinCount >= MinorJackpotMaxRange)
    {
        fire = FireState.Major;
    }
    else if (previousRespinCount >= MinorJackpotMaxRange
        && currentRespinCount == 0)
    {
        fire = FireState.MajorToNone;
    }

    return fire;
}

1 个答案:

答案 0 :(得分:1)

你开始编写单元测试;并使用覆盖率来确定您通过方法了解所有路径。然后你开始重构它,使用众所周知的方法来做到这一点;而且你的测试告诉你,你在前进的过程中不会破坏任何东西。

最后,你扔掉了所有这些;并且您使用TDD重新启动,并专注于提出合理的设计。在你的情况下:你将实现一个状态机......但使用多态;而不是级联的if / else语句。

长话短说:您的选择是进行基于覆盖的重构;或者如果时间允许,重新设计整个组件;因为你当前的实现只是一个伪装很差的状态机。