dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

conditionally compiledGuard API

Open AlgorithmsAreCool opened this issue 6 months ago • 0 comments

Overview

I've been writing some code along a very hot path and I'm finding some tension between wanting the safety of using Guard clauses but also worrying about the runtime overhead.

Has there been any consideration of defining a sister API that used ConditionalAttribute to elide these guards/assertions in release builds?

This can be done external to this library via #if DEBUG but there is some precedent with the Debug.Assert family of methods.

API breakdown

public static class DebugGuard //Open to any other name...
{
    [ConditionalAttribute("Debug")] 
    public static void IsGreaterThan<T>(T value, T minimum, [CallerArgumentExpression(nameof(value))] string name = "");
    
    [ConditionalAttribute("Debug")] 
    public static void IsGreaterThanOrEqualTo<T>(T value, T minimum, [CallerArgumentExpression(nameof(value))] string name = "");
...
}

Usage example

public void MyHotPath(int index)
{
    DebugGuard.IsGreaterThanOfEqualTo(index, 0);
    DebugGuard.IsLessThanOf(index, SomeLimit);
}

Breaking change?

No

Alternatives

public void MyHotPath(int index)
{
#if DEBUG
    Guard.IsGreaterThanOfEqualTo(index, 0);
    Guard.IsGreaterThanOfEqualTo(index, 0);
#endif
}

Additional context

No response

Help us help you

Yes, but only if others can assist

AlgorithmsAreCool avatar Aug 28 '24 00:08 AlgorithmsAreCool