C#
Sam Lau  

Why you should use early return in C#?

Today, I am going to share a simple technique that can improve the readability of your code: early return pattern.

What is early return?

In a method, there are usually the happy path (main logic) and the unhappy path (invalid input, invalid operation, etc.). Early return pattern is writing code such that when an unhappy path is hit, it returns immediately.

I will give an example:

public User InsertUser(int id, string username)
{
    if (IsValidId(id))
    {
        var user = CreatUserWithId(id);
        if (user != null)
        {
            var isValidUserName = user.RegisterUserName(username);
            if (isValidUserName)
            {
                AddUser(user);
                return user;
            }

            throw new InValidUserNameException();
        }

        throw new UnableToCreateUserException();
    }

    throw new UserIdInvalidException();
}

This is basically a method to insert user with some validation check and handling error if fail to create user. It is relatively common user case where you need to do some operation but you have to validate input or other methods’ output along the way.

With early return, this will be refactor to:

public User InsertUser(int id, string username)
{
    if (!IsValidId(id))
    {
        throw new UserIdInvalidException();
    }

    var user = CreatUserWithId(id);

    if (user == null)
    {
        throw new UnableToCreateUserException();
    }

    var isValidUserName = user.RegisterUserName(username);

    if (!isValidUserName)
    {
        throw new InValidUserNameException();
    }

    AddUser(user);
    return user;
}

As you can see, whenever an unhappy path happens, it returns (throw exception in this case) right at the spot inside the if block instead of after the if block.

Why early return?

I am not going to argue which style looks better. It is purely subjective. I will argue in terms of cognitive load.

People read code top to bottom in general. Reading the first code block require the reader to keep information in the head more often. Inside the if(IsValidId(id)) block, people generally will keep this information (id is valid) in mind in case the else block have some other logic. After a couple if block, it is easy to feel lost on the condition and context, especially if there is some else block in between.

Doing early return signals the reader that the path is an unhappy one and reader don’t have to keep that condition in mind. Reader can as a result focus on the happy path.

The other side benefit is that the happy path return will be at the bottom of the method. It makes back tracking the logic a bit easier, comparing to the first method, where the happy return is in the middle of the method.

Conclusion

I hope this short article give you some insight into writing readable code. If you are interest in reducing cognitive load in software engineering in general, this is a good read.