C
C
Coline2020-03-10 12:10:09
C++ / C#
Coline, 2020-03-10 12:10:09

How to refactor nested if else?

There is a class with a set of states. This class has N functions. Each function must do one thing or another depending on the current state, checking input along the way. In the end, each function looks like something like

private void FuncN(string[] params)
{
    if (CheckFuncNParams(params))
        if (state == State.StateX)
            if (collection.ContainsKey(params[2]))
                index++;
            else
                Console.WriteLine("error message 3");
        else
            Console.WriteLine("error message 2");
    else
       Console.WriteLine("error message 1");
}

You can expand the checks to linear ones, but I don’t know how much better this made it
private void FuncN(string[] params)
{
    if (!CheckFuncNParams(params))
    {
        Console.WriteLine("error message 1");
        return;
    }
    if (state != State.StateX)
    {
        Console.WriteLine("error message 2");
        return;
    }
    if (collection.ContainsKey(params[2]))
        index++;
    else
        Console.WriteLine("error message 3");
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DanielMcRon, 2020-03-10
@DanielMcRon

It is necessary to move everything into methods. And the text that is entered in Console.WriteLine is generated depending on the error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question