DEV Community

Cover image for How to Avoid Multiple Nested If-Else Statements Using Guard Clause
Emmanuel Pangan
Emmanuel Pangan

Posted on • Updated on

How to Avoid Multiple Nested If-Else Statements Using Guard Clause


Watch the full video on YouTube.

Guard Clause is a nice trick to reduce nested if statements in your codes.

Let’s say we have this rudimentary UserLogIn. Our eyes will look up and down constantly just to read this whole code.

private static void UserLogIn(bool hasUsername, bool hasPassword, bool isAdmin)
{
    if (hasUsername)
    {
        Console.WriteLine("Username");
        if (hasPassword)
        {
            Console.WriteLine("Password");
            if (isAdmin)
            {
                GoToAdminPage();
            }

            else
            {
                GoToWelcomePage();
            }
        }

        else
        {
            Console.WriteLine("No Password Found.");
        }
    }

    else
    {
        Console.WriteLine("No Username Found.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, to simplify this, we can:

Add a ! here beside this hasUsername, and move this whole block outside, and put this line beneath our new if statement. While deleting the last else. And add a return.

if (!hasUsername)
{
    Console.WriteLine("No Username Found.");
    return;
}

Console.WriteLine("Username");
// Whole block goes here.
Enter fullscreen mode Exit fullscreen mode

In this way, we can exit our method far more quickly while checking if our hasUsernameis false or not. This way, our code is far cleaner and easier to read.

Now, we can also do the same with the other nested if statements.

if (!hasPassword)
{
    Console.WriteLine("No Password Found.");
    return;
}

Console.WriteLine("Password");
if (!isAdmin)
{
    GoToWelcomePage();
    return;
}

GoToAdminPage();
Enter fullscreen mode Exit fullscreen mode

And when debug, we can see that it really works.

Alternatively, instead of adding a return here, we can throw our own Exception.

if (!hasUsername)
{
    throw new Exception("No Username Found");
}

Console.WriteLine("Username");
if (!hasPassword)
{
    throw new Exception("No Password Found");
}

Console.WriteLine("Password");
Enter fullscreen mode Exit fullscreen mode

But for Unity users, this will cause a headache to your game if used for gameplays, and other intensive mechanics, so this is not recommended.

And there you have it, we made this whole if-else statement from unreadable mess into a clean, and readable code.

Here's the final code you can view on GitHub Gist.

Thanks for reading! 📖

Making free programming blogs like this takes a long time of planning, writing, and editing. You can help me through support by: Buying me a Ko-fi ☕.

Check out my YouTube channel for more coding tutorials. Happy coding everyone! 🧡

Top comments (2)

Collapse
 
marco_cabrera_81e1796f41f profile image
marco cabrera

Good job it definitely looks better. If you haven’t checked out pattern matching it could help reduce your code a bit more. learn.microsoft.com/en-us/dotnet/c...

Collapse
 
emmanuel-pangan profile image
Emmanuel Pangan

Thanks for the nice comment. Quite new to Pattern Matching so will check that C# feature out.