LESSON 4 OF 22

4. Implementing Domain Rules, Enums, and Business Constraints

Learn how to use enums, constants, and behavior-focused methods in the Domain layer to protect valid object states and enforce business rules independently.

45 dk 106

Introduction

In the previous lesson, we designed entities and value objects in the Domain layer. In this lesson, we will move beyond entities that merely carry data. In a real application, the domain model must understand which states are valid, reject invalid operations, and protect business rules internally.

For example, after an order is created, we should not allow any caller to assign Shipped directly to its Status property. The order may need to be prepared before it can be shipped. Likewise, adding a product to a cancelled order or adding a negative quantity should be rejected.

We will use an order management scenario throughout this lesson. We will define valid order states with an OrderStatus enum, centralize immutable business values with constants, and manage state transitions through entity methods.

Why should domain rules be protected inside the entity?

Implementing a business rule only in a controller, service, or persistence layer creates a fragile design. The same entity may be created or modified through different entry points. An HTTP endpoint, a background job, or a unit test may interact with the entity directly.

If rules exist only in outer layers, every caller must repeat the same checks. Over time, these checks become inconsistent. One controller may validate a negative quantity while another entry point forgets to do so.

The primary responsibility of the Domain layer is to keep entities meaningful and valid. Outer layers request an operation; the entity decides whether that operation is allowed according to business rules.

Modeling valid states with an enum

A C# enum represents a limited set of named constants. Instead of storing an order status as free-form text, we can use an enum to reduce spelling mistakes and make the model easier to understand.

namespace CleanShop.Domain.Orders;

public enum OrderStatus
{
    Draft = 0,
    Confirmed = 1,
    Preparing = 2,
    Shipped = 3,
    Delivered = 4,
    Cancelled = 5
}

Each state has an explicit name. Assigning explicit numeric values can help preserve the meaning of existing data if the declaration order changes later. This is especially important when enum values are stored as numbers in a database.

A starting state such as Draft makes the lifecycle explicit. If zero should not represent a valid business state, you can define Unknown = 0 and assign a valid state explicitly when constructing the entity.

Validating enum values at the API boundary

Using an enum does not mean that every incoming number is valid. If a client submits 99, the application must verify whether that value is defined. We will cover request validation in more detail later. However, domain methods must still reject invalid transitions and must not blindly trust external input.

Centralizing domain values with constants

Instead of scattering magic numbers and strings throughout the domain model, represent meaningful business values with named constants. For example, the maximum quantity per order item and the minimum order total can be defined as follows:

namespace CleanShop.Domain.Orders;

public static class OrderRules
{
    public const int MaximumItemQuantity = 100;
    public const decimal MinimumOrderTotal = 1m;
    public const int MaximumItemCount = 50;
}

A dedicated class makes the rules easier to find and review. However, not every value should become a constant. Centralize values that have a clear domain meaning and are used in multiple places.

Values that may change through business configuration should not necessarily be compiled into the Domain project. For example, if the maximum order amount is configurable by the business, it may be better represented by a policy or an application setting. In contrast, an invariant such as “quantity must be greater than zero” can remain inside the domain model.

Protecting entity behavior through methods

Public setters allow external code to modify an entity without respecting its rules. Instead, make setters private and expose meaningful behavior methods.

namespace CleanShop.Domain.Orders;

public sealed class Order
{
    private readonly List<OrderItem> _items = new();

    private Order()
    {
        // Available for the ORM.
    }

    public Order(Guid customerId)
    {
        if (customerId == Guid.Empty)
            throw new ArgumentException("CustomerId cannot be empty.", nameof(customerId));

        Id = Guid.NewGuid();
        CustomerId = customerId;
        Status = OrderStatus.Draft;
        CreatedAtUtc = DateTime.UtcNow;
    }

    public Guid Id { get; private set; }
    public Guid CustomerId { get; private set; }
    public OrderStatus Status { get; private set; }
    public DateTime CreatedAtUtc { get; private set; }
    public IReadOnlyCollection<OrderItem> Items => _items.AsReadOnly();

    public decimal Total => _items.Sum(item => item.Total);
}

The public constructor receives required data. CustomerId cannot be empty, and a new order always starts in the Draft state. This makes it harder for callers to create an incomplete or meaningless order.

Applying the add-item rule

Let us define the behavior for adding an item. The quantity must be positive, the per-line maximum must not be exceeded, and cancelled, shipped, or delivered orders must not be modified.

public void AddItem(Guid productId, decimal unitPrice, int quantity)
{
    EnsureEditable();

    if (productId == Guid.Empty)
        throw new ArgumentException("ProductId cannot be empty.", nameof(productId));

    if (unitPrice < 0)
        throw new ArgumentOutOfRangeException(nameof(unitPrice), "Unit price cannot be negative.");

    if (quantity <= 0 || quantity > OrderRules.MaximumItemQuantity)
        throw new ArgumentOutOfRangeException(nameof(quantity), "Quantity must be within the valid range.");

    var existingItem = _items.SingleOrDefault(item => item.ProductId == productId);

    if (existingItem is null)
    {
        if (_items.Count >= OrderRules.MaximumItemCount)
            throw new InvalidOperationException("The order reached the maximum number of item lines.");

        _items.Add(new OrderItem(productId, unitPrice, quantity));
        return;
    }

    existingItem.IncreaseQuantity(quantity);
}

The EnsureEditable method prevents the same state check from being repeated in every behavior method.

private void EnsureEditable()
{
    if (Status is OrderStatus.Cancelled or OrderStatus.Shipped or OrderStatus.Delivered)
        throw new InvalidOperationException("An order in this state cannot be modified.");
}

The exception type is meaningful. Use ArgumentException or a derived type when an input parameter is invalid. Use InvalidOperationException when the entity’s current state does not allow the requested operation. The Application or Presentation layers can later translate these failures into appropriate API responses.

Defining state transitions explicitly

Rather than allowing callers to assign enum values directly, control every transition through a method. This makes the workflow visible and keeps transition rules in one place.

public void Confirm()
{
    if (Status != OrderStatus.Draft)
        throw new InvalidOperationException("Only a draft order can be confirmed.");

    if (_items.Count == 0)
        throw new InvalidOperationException("An order without items cannot be confirmed.");

    if (Total < OrderRules.MinimumOrderTotal)
        throw new InvalidOperationException("The order total is below the minimum amount.");

    Status = OrderStatus.Confirmed;
}

public void StartPreparing()
{
    EnsureStatus(OrderStatus.Confirmed);
    Status = OrderStatus.Preparing;
}

public void Ship()
{
    EnsureStatus(OrderStatus.Preparing);
    Status = OrderStatus.Shipped;
}

public void Deliver()
{
    EnsureStatus(OrderStatus.Shipped);
    Status = OrderStatus.Delivered;
}

public void Cancel()
{
    if (Status is OrderStatus.Shipped or OrderStatus.Delivered)
        throw new InvalidOperationException("A shipped or delivered order cannot be cancelled.");

    if (Status == OrderStatus.Cancelled)
        throw new InvalidOperationException("The order is already cancelled.");

    Status = OrderStatus.Cancelled;
}

private void EnsureStatus(OrderStatus expectedStatus)
{
    if (Status != expectedStatus)
        throw new InvalidOperationException($"This operation is allowed only when the status is {expectedStatus}.");
}

This structure keeps the workflow inside the domain model instead of distributing it across controller if statements. The Application layer only loads the order and calls the appropriate method.

Designing OrderItem

The OrderItem should protect its own rules as well. Product identity, price, and quantity should not be changed freely from outside the object.

public sealed class OrderItem
{
    private OrderItem()
    {
    }

    public OrderItem(Guid productId, decimal unitPrice, int quantity)
    {
        if (productId == Guid.Empty)
            throw new ArgumentException("ProductId cannot be empty.", nameof(productId));

        if (unitPrice < 0)
            throw new ArgumentOutOfRangeException(nameof(unitPrice));

        if (quantity <= 0)
            throw new ArgumentOutOfRangeException(nameof(quantity));

        Id = Guid.NewGuid();
        ProductId = productId;
        UnitPrice = unitPrice;
        Quantity = quantity;
    }

    public Guid Id { get; private set; }
    public Guid ProductId { get; private set; }
    public decimal UnitPrice { get; private set; }
    public int Quantity { get; private set; }
    public decimal Total => UnitPrice * Quantity;

    public void IncreaseQuantity(int quantity)
    {
        if (quantity <= 0)
            throw new ArgumentOutOfRangeException(nameof(quantity));

        if (Quantity + quantity > OrderRules.MaximumItemQuantity)
            throw new InvalidOperationException("The quantity cannot exceed the allowed maximum.");

        Quantity += quantity;
    }
}

Mapping enums with EF Core

When the domain model uses an enum, EF Core can store it as a number or as text. Numeric storage requires less space, while text storage is easier to read when inspecting database records.

builder.Property(order => order.Status)
    .HasConversion<string>()
    .HasMaxLength(32)
    .IsRequired();

Storing enum values as text can reduce confusion related to numeric values. However, renaming an enum member may affect existing rows. Any rename should therefore be planned together with a migration and, if necessary, a data update.

Business rules versus technical validation

Whether a field is required or whether a string exceeds its maximum length is usually input validation. Whether an order can be confirmed only while it is in the draft state is a domain business rule.

  • Input validation: Can be handled in request models, DTOs, or FluentValidation.
  • Domain rule: Must remain valid whenever the entity is used, regardless of the entry point.
  • Database constraint: Protects persistence concerns such as uniqueness, foreign keys, and nullability.

These layers complement one another. The API can validate input for fast feedback, while the entity remains the final protection for its own invariants.

Common mistakes

  • Using public setters: Every property can be changed externally, making the entity uncontrolled and anemic.
  • Using strings instead of enums: Spelling mistakes and unsupported values become more likely. If strings are required, centralize them carefully.
  • Putting transitions in controllers: The same workflow is duplicated across entry points and becomes inconsistent.
  • Turning every value into a constant: Business settings that may change should not be hard-coded into the domain model.
  • Coupling exception messages to HTTP: The Domain layer should not know about HTTP status codes or API response contracts.
  • Making the ORM constructor broadly public: If a parameterless constructor is required, keep its accessibility as restricted as the ORM allows.

Short practice exercise

Apply the following exercise to the existing solution:

  1. Add a Returned state to the OrderStatus enum.
  2. Implement a Return method that prevents an order from being returned before delivery.
  3. Prevent items from being added to cancelled or returned orders.
  4. Write tests for these scenarios: an empty order cannot be confirmed, the correct state sequence is followed, and invalid transitions throw exceptions.
  5. Configure EF Core to store enum values as strings.

When writing tests, cover rejected scenarios as carefully as successful scenarios. Domain tests should run without a database or web server.

Conclusion

In this lesson, we turned the Domain layer from a collection of entity properties into a model that also contains behavior and business rules. Enums made valid states explicit, constants centralized immutable domain values, and private setters plus methods protected entity integrity.

The key idea is to request meaningful behavior instead of assigning raw values. Calling order.Ship() is safer than writing order.Status = OrderStatus.Shipped, because the transition rules remain inside the model and the rest of the application stays simpler.

In the next lessons, we will see how to use this domain model from Application-layer use cases and how to define contracts between the layers.

Sources