DEV Community

Cover image for Validation in DDD Applications: Protecting Domain Rules
Rodrigo de Oliveira
Rodrigo de Oliveira

Posted on Edited on

Validation in DDD Applications: Protecting Domain Rules

Learn how to distribute validation responsibilities, preserve invariants, and build consistent domain models without turning your application into a collection of scattered checks.

This article is part of our ongoing series on Domain-Driven Design (DDD). In the previous article, Aggregates and Aggregate Roots: Designing Consistency Boundaries, we discussed how aggregates help establish clear boundaries for maintaining data consistency.

Now, let's explore a closely related question: How can we ensure that our data remains valid throughout an application's lifecycle?

When we talk about validation, we often think about checking whether a field is required, whether a number is positive, or whether an email address follows an acceptable format.

These checks are important, but they represent only part of the problem.

In applications built around Domain-Driven Design, validation also means protecting the rules that define how the business operates. It means preventing an entity from entering an inconsistent state, even when an operation involves multiple services, integrations, or processes.

And this brings us to an important distinction: Not every validation belongs in the domain, but every rule essential to domain consistency must be protected.

Let's explore what this means in practice.


Validating Data Is Not the Same as Validating the Domain

Imagine an e-commerce application where customers can create orders, add products, and confirm purchases.

When the application receives a request to add an item, we might check whether the product identifier was provided and whether the quantity is greater than zero.

These are relatively simple validations, usually performed before executing the use case.

Now consider a few other situations:

  • A confirmed order cannot accept additional items.
  • An order cannot be confirmed without products.
  • An order item cannot have a quantity of zero or less.
  • A canceled order cannot transition directly back to the confirmed state.

Notice that we're no longer simply checking incoming data. We're protecting behaviors and states allowed by the business.

An application can receive a technically valid request that still represents an invalid business operation.

For example, adding five products to an order that has already been confirmed.

The data is valid. The operation is not.

This distinction helps explain why validation should not be concentrated exclusively in controllers, DTOs, or specialized validation libraries.

Invariants: The Rules That Must Remain True

One of the most important concepts when discussing validation in DDD is the domain invariant.

An invariant represents a condition that must remain true for an object or aggregate to be considered valid.

In Domain-Driven Design: Tackling Complexity in the Heart of Software, Eric Evans emphasizes the importance of preserving model integrity. Vaughn Vernon explores this further by connecting invariants to aggregate consistency boundaries.

However, this doesn't mean every rule must be satisfied at every stage of a business process.

Let's return to our order example.

While an order is in draft status, it may contain no items at all. That's perfectly acceptable.

However, before transitioning to the confirmed state, the order must contain at least one product.

Therefore, the invariant isn't simply:

"Every order must contain items."

The correct business rule is:

"Every confirmed order must contain at least one item."

That small distinction significantly changes the implementation.

The domain needs to represent legitimate business states and control transitions between them.

A common mistake is treating an object as invalid simply because it hasn't reached its final state. In many business processes, intermediate states are perfectly valid.

The challenge is identifying which conditions must remain true in each state.

Where Should Each Validation Take Place?

A recurring question is where validations should be implemented.

In practice, no single layer should be responsible for every type of validation.

A useful approach is to separate responsibilities across input validation, application orchestration, domain behavior, and persistence.

Input Validation

The first concern is ensuring that incoming data meets the expected contract.

We can use Data Annotations, FluentValidation, or similar mechanisms supported by our technology stack.

In .NET, for example, we could represent a request like this:

public sealed record AddOrderItemCommand(
    Guid OrderId,
    Guid ProductId,
    int Quantity);
Enter fullscreen mode Exit fullscreen mode

And create a validator:

public sealed class AddOrderItemCommandValidator
    : AbstractValidator<AddOrderItemCommand>
{
    public AddOrderItemCommandValidator()
    {
        RuleFor(x => x.OrderId)
            .NotEmpty();

        RuleFor(x => x.ProductId)
            .NotEmpty();

        RuleFor(x => x.Quantity)
            .GreaterThan(0);
    }
}
Enter fullscreen mode Exit fullscreen mode

This validator ensures that the request contains the necessary information and that the values meet the defined constraints.

It can prevent obviously invalid requests from moving further into the application.

But there's still a problem.

Nothing in this code guarantees that the order is open for modifications.

The validator doesn't even know the current state of the order.

And that's perfectly fine. It doesn't have to.

Input validation acts as the first line of defense, but it doesn't replace domain rules.

Validation in the Application Layer

The application layer coordinates the execution of use cases.

It may load aggregates, query services, check prerequisites, and orchestrate the necessary operations.

Imagine that before adding a product, we need to verify whether the order exists.

An Application Service or Command Handler can query the repository and report that the order was not found.

It might also retrieve the current product price from an authoritative source rather than trusting a value supplied directly by the client.

However, the application layer shouldn't be responsible for deciding whether a confirmed order can accept additional items.

That decision belongs to the domain.

One way to understand this separation is:

The application coordinates what needs to happen. The domain determines what is allowed to happen.

This separation prevents essential business rules from becoming scattered across different handlers and services.

Validation in the Domain

Now we reach the core of the discussion.

Within the domain model, validations must protect invariants and control business operations.

Let's represent an Order aggregate in a simplified way:

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

    public IReadOnlyCollection<OrderItem> Items
        => _items.AsReadOnly();

    public OrderStatus Status { get; private set; }
        = OrderStatus.Draft;

    public void AddItem(
        Guid productId,
        int quantity,
        decimal unitPrice)
    {
        if (Status != OrderStatus.Draft)
            throw new BusinessRuleException(
                "The order does not allow new items.");

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

    public void Confirm()
    {
        if (Status != OrderStatus.Draft)
            throw new BusinessRuleException(
                "The order cannot be confirmed.");

        if (_items.Count == 0)
            throw new BusinessRuleException(
                "The order must contain items.");

        Status = OrderStatus.Confirmed;
    }
}
Enter fullscreen mode Exit fullscreen mode

Illustrative example: OrderItem must also protect its own values, such as requiring a positive quantity and a non-negative unit price.

Notice that we don't expose a public method for changing Status directly.

We also don't expose the internal collection for external modification.

Instead, the aggregate's state changes through behaviors that represent business operations.

This matters because allowing unrestricted property changes would enable any part of the application to put the order into an inconsistent state.

The entity protects its own rules.

And as we discussed in the previous article, the Aggregate Root serves as the entry point for operations that must preserve the consistency of the aggregate.

Value Objects Must Also Protect Their Validity

Entities aren't the only components responsible for enforcing rules.

Value Objects also play an important role.

Imagine an object representing a product quantity.

One possible implementation would be:

public readonly record struct Quantity
{
    public int Value { get; }

    public Quantity(int value)
    {
        if (value <= 0)
            throw new ArgumentOutOfRangeException(
                nameof(value),
                "Quantity must be positive.");

        Value = value;
    }
}
Enter fullscreen mode Exit fullscreen mode

This approach communicates an important rule: an item quantity must be positive.

However, C# has an interesting detail worth considering: a struct can assume its default value without executing its custom constructor.

As a result, default(Quantity) could still produce a quantity of zero.

If an absolute validity guarantee is important, we might choose an immutable reference type, carefully control object creation, or explicitly handle default values.

This detail illustrates something I consider essential: Adding validation to a constructor doesn't automatically mean every possible object creation path is protected.

We need to understand the language and the mechanisms involved in materialization, serialization, and persistence.

The purpose of a Value Object is to provide a meaningful and reliable representation of a domain concept.

When properly modeled, it reduces the need to repeat the same validations throughout the system.

Exceptions, Result, and Notification: How Should We Communicate Failures?

So far, we've used exceptions to prevent invalid operations.

That works, but should we use exceptions for every validation failure?

Not necessarily.

There's an important difference between encountering a truly exceptional condition and handling an expected business rejection.

Consider confirming an empty order.

Depending on the context, this may be a common and predictable situation. It might be better to communicate the outcome without relying on exception-based control flow.

One alternative is the Result pattern.

public Result Confirm()
{
    if (Status != OrderStatus.Draft)
        return Result.Failure(
            "order.invalid_state",
            "The order cannot be confirmed.");

    if (_items.Count == 0)
        return Result.Failure(
            "order.no_items",
            "Add at least one item before confirming.");

    Status = OrderStatus.Confirmed;

    return Result.Success();
}
Enter fullscreen mode Exit fullscreen mode

This example replaces the previous Confirm implementation. Result represents a custom application or domain type, not a built-in C# feature.

Now the operation explicitly communicates success or failure.

The code executing the use case can interpret that outcome and decide how to present it to the consumer.

Martin Fowler also describes the Notification pattern as an alternative when we want to collect multiple validation problems.

Instead of stopping at the first issue, we can accumulate relevant errors and report them together.

This is particularly useful for forms, complex commands, and processes where the consumer benefits from seeing all validation issues at once.

But there's an important consideration.

Collecting errors doesn't mean allowing an invalid entity to be modified or persisted.

We can identify multiple failures before performing a state transition. If any essential rule isn't satisfied, the operation should be rejected without leaving partial changes behind.

My preference is to choose the approach based on the nature of the failure:

  • Result: When rejection is an expected outcome of an operation.
  • Notification: When collecting multiple validation problems is useful.
  • Exceptions: When something exceptional occurs, an unexpected contract violation is detected, or the design explicitly chooses exceptions to enforce invariants.

There's no reason to turn this decision into a competition between patterns.

What matters is maintaining a consistent strategy that fits the domain.

What Happens When a Rule Depends on External Information?

So far, we've discussed rules that can be evaluated using information available within the aggregate.

But that's not always enough.

Imagine an application where every customer must have a unique registration identifier.

To verify whether an identifier already exists, we may need to query a database.

Would injecting a repository directly into the Customer entity be a good idea?

In most cases, I would avoid it.

Entities and Value Objects should concentrate domain behaviors and concepts without becoming unnecessarily coupled to infrastructure.

When a rule depends on external information, we can use the application layer to coordinate queries or introduce a Domain Service when the decision represents business logic that doesn't naturally belong to a specific entity.

We can also represent more complex business policies through the Specification pattern, especially when we need to encapsulate and reuse decision criteria.

However, there's another problem we need to consider: concurrency.

Imagine two simultaneous requests attempting to register the same identifier.

Both query the database.

Both discover that the identifier doesn't exist yet.

Both attempt to save their changes.

The earlier validation doesn't guarantee uniqueness.

That's why, when consistency depends on persistence, additional mechanisms such as unique indexes, transactions, and concurrency control are important.

Validation in the domain or application layer helps express the rule and anticipate a rejection. The database constraint protects data integrity when concurrent operations occur.

These responsibilities complement one another.

Validation Across Aggregates: Respecting Consistency Boundaries

In the previous article, we discussed how aggregates represent consistency boundaries.

This concept also directly influences validation.

Within an aggregate, invariants requiring immediate consistency must be preserved during its operations.

However, when a rule involves multiple aggregates, we need to evaluate whether an atomic update is genuinely necessary.

In some scenarios, eventual consistency is sufficient.

Imagine that confirming an order must initiate an inventory allocation process.

We might confirm the order and publish a domain event that triggers an operation in another aggregate.

But there's an important difference between a consequence of confirmation and a mandatory prerequisite.

If the business requires inventory reservation to be guaranteed before an order is confirmed, simply publishing an event and waiting for later processing does not satisfy that rule.

In that situation, the model must correctly represent the reservation, its states, and the coordination required.

Vaughn Vernon emphasizes this relationship between invariants and consistency boundaries in his work on aggregate design.

The point is that we shouldn't automatically introduce distributed transactions or enlarge aggregates simply because a rule involves multiple business concepts.

First, we need to understand which consistency guarantees the business actually requires.

Then we can choose the appropriate mechanism.

The Risk of Validating Everything in One Place

There's a common temptation in .NET projects: centralizing nearly every rule in classes implementing AbstractValidator.

The idea is appealing.

We have a specialized library, readable syntax, and a standardized mechanism for reporting errors.

The problem begins when essential business rules exist exclusively in those validators.

Imagine a validator that checks whether an order is open, whether sufficient balance is available, whether a customer may perform an operation, and whether a particular state transition is allowed.

If those rules exist only in that layer, other execution paths may bypass them.

Applications don't receive commands exclusively through HTTP APIs.

They may also be triggered by message consumers, scheduled jobs, integrations, and internal processes.

When the aggregate itself protects the rule, all those execution paths must respect it.

This doesn't prevent us from using FluentValidation to improve input handling or perform early checks.

It simply means the library shouldn't become the sole guardian of the domain model.

External validators help reject invalid requests. The domain must prevent invalid states.

How Should We Test Validations?

One advantage of keeping invariants inside the domain is that we can test them without depending on an API or a database.

We can write unit tests that directly exercise aggregate behaviors.

For our Order example, important scenarios include verifying that an empty order cannot be confirmed, that a draft order accepts valid items, and that a confirmed order rejects further modifications.

We also need to test successful paths.

An operation that should be allowed must not be incorrectly blocked by an overly restrictive rule.

These tests represent actual business expectations.

Application-level tests can verify how outcomes are handled, how dependencies are coordinated, and how external information influences decisions.

Finally, integration tests are important for validating database constraints, transactional behavior, and concurrency conflict handling.

A uniqueness rule, for example, isn't completely tested just because a repository query returned the expected result.

We also need to ensure persistence rejects incompatible writes.

Ideally, our tests should answer not only whether a condition was checked, but whether the application can actually prevent a business rule from being violated.

References and Further Reading

For those interested in exploring these concepts further, I recommend the following resources:

Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software. The foundational book for understanding entities, Value Objects, aggregates, and model integrity.

Vaughn Vernon, Implementing Domain-Driven Design. A deeper exploration of tactical modeling, including validation, invariants, and aggregate consistency.

Vaughn Vernon, Domain-Driven Design Distilled. A more concise introduction to the essential concepts and responsibilities within the domain model.

Vaughn Vernon, Effective Aggregate Design. A series of articles explaining how to identify invariants and establish appropriate consistency boundaries.

FluentValidation Official Documentation. A useful resource for implementing strongly typed input validation in .NET applications while understanding its capabilities and limitations.

Top comments (0)