lundi 17 décembre 2018

How to refactor deeply nested functions?

My code currently looks like this:

If (case = 1)
{
    If (option = 1)
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
    else
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
}

else if (case = 2)
{
    If (option = 1)
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
    else
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
}

else if (case = 3)
{
    If (option = 1)
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
    else
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
}

Obviously terrible and difficult to maintain. I want to add yet another super If statement on top of this, which splits this tree 6 times. Each ;do something does one line of code.

Any help on how to refactor this monstrosity? I've written a lot of code that looks like this and I dread working with it every time. I need a new way to approach these problems. Extending the functionality of this code requires a lot of work.

Aucun commentaire:

Enregistrer un commentaire