Search code examples
c#domain-driven-design

Unsigned number instead of checking invariant in DDD


If you know a number cannot be negative, which design is better in a DDD model?

public record Quantity(uint Number);
public record Quantity()
{
    public int number { get; init; }
    public Quantity(int number)
    {
        if (number < 0) throw new ArgumentOutOfRangeException("Quantity must be positive");
    }
}

Solution

  • If you know a number cannot be negative, which design is better in a DDD model ?

    I can't think of a single DDD example I have seen that uses unsigned types as a general purpose data structure.

    The general rule for unsigned types is that you use default to using a signed type, and use unsigned types only when appropriate to the specific task at hand.

    Google C++ Style Guide

    Do not use an unsigned type merely to assert that a variable is non-negative.

    CPP Core Guidelines: ES106

    Don't try to avoid negative values by using unsigned

    Stroustrup, Sutter and Carruth were of unanimous opinion in 2013

    Online discussions that agree with the above