lundi 19 octobre 2015

How to avoid long if-else chains?

I have long if-else chains in my code. Something like

public void SomeMethod()
{
    if (Condition1)
    {
        DoAction1();
        return;
    }
    ...
    if (ConditionN)
    {
        DoActionN();
        return;
    }
}

I have implemented a simple class for such scenarios.

public class ActionChain
{
    private bool isFinished;

    public ActionChain EndIf(Func<bool> action)
    {
        if (isFinished)
        {
            return this;
        }
        isFinished = action();
        return this;
    }

    public void Perform(Action action)
    {
        if (isFinished)
        {
            return;
        }
        action();
    }
}

Now I can handle such cases like

public void SomeMethod()
{
     new ActionChain()
     .EndIf(Action1)
     ...
     .EndIf(ActionN);
}

Does someone know any better solution? How do you handle long if-else chains?

Aucun commentaire:

Enregistrer un commentaire