Resharper Ninja Tip

If you find a method with deep nested if statements, use a combination of "Invert ‘if’" and "Remove redundant else" from Resharper’s Quick-Fix menu (ALT+ENTER) to flatten it all out nicely. Makes it much easier to "return early" and means you don’t have to worry you’ve screwed up the actual logic too much in the process because R# deals with swopping the boolean logic in the if statements for you.

Here’s a super-contrived example:

Before:

public void MyMethod(string parameter)
{
    if (parameter.Substring(0, 1) == “A”)
    {
        if (parameter.Substring(0, 2) == “B”)
        {
            if (parameter.Substring(0, 3) == “C”)
            {
                if (parameter.Substring(0, 4) == “D”)
                {
                    if (parameter.Substring(0, 5) == “E”)
                    {
                        DoSomethingCool(parameter);
                    }
                    else
                    {
                        throw new ArgumentException(“Parameter[4] is invalid”);
                    }
                }
                else
                {
                    throw new ArgumentException(“Parameter[3] is invalid”);
                }
            }
            else
            {
                throw new ArgumentException(“Parameter[2] is invalid”);
            }
        }
        else
        {
            throw new ArgumentException(“Parameter[1] is invalid”);
        }
    }
    else
    {
        throw new ArgumentException(“Parameter[0] is invalid”);
    }
}

After:

public void MyMethod2(string parameter)
{
    if (parameter.Substring(0, 1) != “A”) throw new ArgumentException(“Parameter[0] is invalid”);
    if (parameter.Substring(0, 2) != “B”) throw new ArgumentException(“Parameter[1] is invalid”);
    if (parameter.Substring(0, 3) != “C”) throw new ArgumentException(“Parameter[2] is invalid”);
    if (parameter.Substring(0, 4) != “D”) throw new ArgumentException(“Parameter[3] is invalid”);
    if (parameter.Substring(0, 5) != “E”) throw new ArgumentException(“Parameter[4] is invalid”);

    DoSomethingCool(parameter);
}

Hope this helps 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s