본문 바로가기

C#

[C#] Guard Clause

public static void SampleMethod(int[] array, int index, Span<int> span, string text)
{
    if (array is null)
    {
        throw new ArgumentNullException(nameof(array), "The array must not be null");
    }

    if (array.Length >= 10)
    {
        throw new ArgumentException($"The array must have less than 10 items, had a size of {array.Length}", nameof(array));
    }

    if (index < 0 || index >= array.Length)
    {
        throw new ArgumentOutOfRangeException(nameof(index), $"The index must be in the [0, {array.Length}) range, was {index}");
    }

    if (span.Length < array.Length)
    {
        throw new ArgumentException($"The target span is shorter than the input array, had a length of {span.Length}", nameof(span));
    }

    if (string.IsNullOrEmpty(text))
    {
        throw new ArgumentException("The input text can't be null or empty", nameof(text));
    }
}

위와 같은 코드가 많이 보이는데,

메소드 시작부터 너무 긴 코드들이 가독성을 해치곤 한다.

 

그런데 Guard clause라는게 있다. 아래와 같은 class를 만들어 사용하면 좀더 간결한 코딩이 가능하다.

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

public void SomeMethod<T>(string var1, IEnumerable<T> items, int count)
{
    Guard.ArgumentIsNotNull(arg1, "arg1");
    
    ..
}

아래처럼 여러가지 guard를 추가해서 사용하면 된다.
public static void SampleMethod(int[] array, int index, Span<int> span, string text)
{
    Guard.IsNotNull(array);
    Guard.HasSizeGreaterThanOrEqualTo(array, 10);
    Guard.IsInRangeFor(index, array);
    Guard.HasSizeLessThanOrEqualTo(array, span);
    Guard.IsNotNullOrEmpty(text);
}

이를 위한 library도 존재한다.

Guard - .NET Community Toolkit | Microsoft Learn
https://github.com/ardalis/GuardClauses
https://www.nuget.org/packages/Ardalis.GuardClauses

 

참조

Guard - .NET Community Toolkit | Microsoft Learn

c# - Refactoring Guard Clauses - Stack Overflow