Search Sreeni's Insights

Filter by content type
crafting March 15, 2016 7 min read

Defensive coding - guard clauses and null checks without the noise

Defensive coding explained through guard clauses, boundary validation, specific exceptions, null checks, empty collections and clearer .NET application logic for practical guidance.

Share:

Defensive coding - guard clauses and null checks without the noise

NullReferenceException is probably the most common exception in the .NET applications. When it happens in production, the stack trace tells us the line number but not which object was null or why it was null. The developer spends hours to reproduce the issue, while the customer is waiting. On the other hand, when developers try to be very careful, the code becomes full of nested if blocks and null checks, and the actual business logic is lost somewhere in the middle.

In the previous article, we discussed whether Test Driven Development (TDD) is worth it for our team. In this article, we are going to see what is defensive coding, how guard clauses help us to fail fast with a clear message, and how to do null checks without making the code noisy.

TL;DR Summary

  • Defensive coding means a method protects itself from invalid inputs and invalid state.
  • Validate at the boundaries (public methods, API controllers), trust inside the boundary.
  • Use guard clauses, check and exit at the top of the method, instead of nested if blocks.
  • Fail fast with a specific exception and a clear message (ArgumentNullException with nameof).
  • Don’t return null for collections, return an empty collection.
  • Use C# 6 null-conditional (?.) and null-coalescing (??) operators to reduce noise, but don’t use them to hide bugs.

Challenges

Late failures

When a method accepts a null argument silently, the failure happens somewhere deep inside, sometimes in a different class or thread. The exception message is “Object reference not set to an instance of an object”, which tells nothing about the root cause. The Mean Time To Resolve (MTTR) is going up because of the investigation time.

Arrow code

When every check is an if block wrapping the rest of the method, the code is growing to the right like an arrow. It is very hard to read, and the else branches with error handling are far from the condition which caused them.

Over-defensive code

Some developers check every variable in every private method, even when it can never be null. It adds noise, hides the real validation rules and makes the reader think “can this really be null here?”.

Swallowing errors

Sometimes, the defensive code catches an invalid state and returns a default value like 0 or null without telling anybody. The application continues with wrong data, and it is much worser than an exception, because nobody knows something went wrong.

What is Defensive coding?

Defensive coding is a practice of writing code that anticipates invalid inputs, invalid state and unexpected conditions, and handles them explicitly so the software continues to behave predictably.

In simple terms, a method should not trust its callers blindly. It should check what it needs at the entry, and if something is wrong, it should stop immediately with a clear reason. It is like a security guard at the entrance of a building, the check happens once at the door, not in every room.

What is a Guard clause?

A guard clause is a check at the beginning of a method which exits immediately (by throwing an exception or returning) when a precondition is not met. After the guards, the rest of the method can assume the inputs are valid.

Let us take an example from our fund domain. Here is a method written with nested checks,

public FundSummary GetFundSummary(string isin, DateTime asOfDate)
{
    if (isin != null)
    {
        if (asOfDate <= DateTime.Today)
        {
            var fund = _fundRepository.GetByIsin(isin);
            if (fund != null)
            {
                var price = _priceService.GetPrice(isin, asOfDate);
                return new FundSummary(fund.Name, price.Value, fund.Currency);
            }
            else
            {
                return null;
            }
        }
        else
        {
            throw new Exception("Invalid date");
        }
    }
    else
    {
        throw new Exception("Invalid input");
    }
}

The same method with guard clauses,

public FundSummary GetFundSummary(string isin, DateTime asOfDate)
{
    if (string.IsNullOrWhiteSpace(isin))
        throw new ArgumentNullException(nameof(isin));

    if (asOfDate > DateTime.Today)
        throw new ArgumentOutOfRangeException(nameof(asOfDate), asOfDate, "As of date cannot be in the future.");

    var fund = _fundRepository.GetByIsin(isin);
    if (fund == null)
        throw new FundNotFoundException(isin);

    var price = _priceService.GetPrice(isin, asOfDate);
    return new FundSummary(fund.Name, price.Value, fund.Currency);
}

The following diagram explains the flow of guard clauses.

Guard clauses flow
Guard clauses flow

The flow highlighted in purple is the happy path. Each guard is a short exit on the side, and the business logic is a straight line at the end, not hidden inside three levels of nesting.

Why Defensive coding is important?

In order to find the problems at the place where they are introduced, to give a clear error message to the caller and to keep the business logic readable, defensive coding with guard clauses is important. A clear ArgumentNullException for parameter isin at the API boundary takes minutes to fix. A NullReferenceException three layers down takes hours. Most importantly, failing fast stops the wrong data from spreading into our database and reports, which is very expensive to clean up later.

Where to validate?

It is not necessary all methods should validate all inputs. We follow a simple rule, validate at the boundaries, trust inside.

LayerWhat to checkHow to fail
Web API controllerRequest model, required fields, rangesReturn 400 Bad Request with validation errors
Public methods of services and librariesArguments (null, empty, range)ArgumentNullException, ArgumentOutOfRangeException
Domain objectsInvariants (ex: units cannot be negative)Domain specific exception
Private methodsUsually nothing, the caller already validated-
External systems (DB, APIs, files)Responses can be null, empty or malformedSpecific exception or a clear fallback

Note: In Web API, use Data Annotations ([Required], [Range]) and check ModelState.IsValid instead of writing guard clauses inside each action. Refer the exception handling article from last year for how we return errors to clients without sending the stack trace.

Null checks without the noise

Here are some practices we follow to reduce the null check noise.

Don’t return null for collections

Return an empty collection instead of null. The caller can use foreach or LINQ without checking.

// Don't
public IList<Price> GetPrices(string isin)
{
    var prices = _repository.FindPrices(isin);
    return prices.Any() ? prices : null;
}

// Do
public IList<Price> GetPrices(string isin)
{
    return _repository.FindPrices(isin) ?? new List<Price>();
}

Use null-conditional and null-coalescing operators

C# 6 (Visual Studio 2015) gives us ?. and nameof, and they remove lot of boilerplate.

var managerName = fund.Manager?.Name ?? "Not assigned";

But be mindful, ?. is for values which can be legally null. If fund.Manager must always exist, ?. is hiding a bug. Use a guard instead.

Use a small Guard helper

When the same checks are repeated in many classes, a small helper keeps them on one line.

public static class Guard
{
    public static void NotNull(object value, string parameterName)
    {
        if (value == null)
            throw new ArgumentNullException(parameterName);
    }

    public static void NotNullOrEmpty(string value, string parameterName)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException("Value cannot be null or empty.", parameterName);
    }
}

// Usage
Guard.NotNullOrEmpty(isin, nameof(isin));

Use the Null Object pattern where it fits

When “nothing” has a valid behaviour, use a null object instead of null. For example, a NullAuditLogger which does nothing, instead of checking if (_logger != null) everywhere.

Must Do and Don’ts

  • Must Do: Validate public inputs at the top of the method with guard clauses.
  • Must Do: Throw specific exceptions with nameof(parameter) and a meaningful message.
  • Must Do: Return empty collections, never null collections.
  • Should: Make domain objects valid on construction, so they cannot exist in an invalid state.
  • Don’t: throw new Exception("Invalid input"), the caller cannot handle it specifically and the message doesn’t help.
  • Don’t: catch an exception and return a default value silently, otherwise wrong data travels further.
  • Don’t: add null checks in private methods for values which are already validated.

Wrap up

In this article, we have looked at what is defensive coding, how guard clauses replace the arrow code, where to validate and some practices to do null checks without the noise. Thanks for reading this article and I hope this article provided you some insights into writing safer and cleaner code. In the next article, I will walk you through how to write maintainable LINQ and Entity Framework queries.

Related Posts