Recipe 8.5 · C#
Validating at the Boundary and Inside the Domain
Problem
Once a team adopts validators, the next question is where to put them. One camp validates only in the controller, and the domain objects accept anything. Another camp repeats every check in every layer until a change to a maximum length requires edits in six places. Neither holds up. The first lets a background job or a second API create invalid objects. The second drifts out of sync.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
public class Order
{
public string CustomerEmail { get; set; }
public List<OrderItem> Items { get; set; }
public string Status { get; set; }
}
// Somewhere far away:
order.Status = "Submitted";
order.Items.Add(new OrderItem { Quantity = -3 });
Public setters on everything mean any code can put the object into any state. The controller's validation is the only line of defense, and only for the paths that go through the controller.
The improved recipe
Split the work in two. At the boundary (API endpoint, file import, message handler) validate the shape of input and collect every error for the caller. Inside the domain, make invalid states impossible to construct: small value objects with a TryCreate factory, and entities whose methods enforce their own rules and throw when a caller breaks them.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net.Mail;
namespace ImproveCode.Validation;
public sealed record EmailAddress
{
private EmailAddress(string value) => Value = value;
public string Value { get; }
public static bool TryCreate(
string? input,
[NotNullWhen(true)] out EmailAddress? email,
[NotNullWhen(false)] out string? error)
{
email = null;
string trimmed = input?.Trim() ?? "";
if (trimmed.Length is 0 or > 254)
{
error = "E-mail must be between 1 and 254 characters.";
return false;
}
if (!MailAddress.TryCreate(trimmed, out var parsed)
|| parsed.Address != trimmed)
{
error = "E-mail is not a valid address.";
return false;
}
email = new EmailAddress(trimmed);
error = null;
return true;
}
public override string ToString() => Value;
}
public enum OrderStatus { Draft, Submitted }
public sealed record OrderItem(string Sku, int Quantity);
public sealed class Order
{
public const int MaxItems = 100;
private readonly List<OrderItem> _items = [];
public Order(EmailAddress customerEmail)
{
ArgumentNullException.ThrowIfNull(customerEmail);
CustomerEmail = customerEmail;
}
public EmailAddress CustomerEmail { get; }
public OrderStatus Status { get; private set; }
public IReadOnlyList<OrderItem> Items => _items;
public void AddItem(string sku, int quantity)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sku);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
EnsureDraft();
if (_items.Count >= MaxItems)
{
throw new InvalidOperationException(
$"An order cannot have more than {MaxItems} items.");
}
_items.Add(new OrderItem(sku.Trim(), quantity));
}
public void Submit()
{
EnsureDraft();
if (_items.Count == 0)
{
throw new InvalidOperationException(
"An empty order cannot be submitted.");
}
Status = OrderStatus.Submitted;
}
private void EnsureDraft()
{
if (Status != OrderStatus.Draft)
{
throw new InvalidOperationException(
"Only draft orders can be changed.");
}
}
}
public sealed record NewOrderDto(
string? Email, IReadOnlyList<NewOrderItemDto>? Items);
public sealed record NewOrderItemDto(string? Sku, int Quantity);
public static class NewOrderMapper
{
public static bool TryMap(
NewOrderDto dto,
[NotNullWhen(true)] out Order? order,
out IReadOnlyList<ValidationError> errors)
{
ArgumentNullException.ThrowIfNull(dto);
var list = new List<ValidationError>();
order = null;
if (!EmailAddress.TryCreate(dto.Email, out var email,
out var emailError))
{
list.Add(new(nameof(dto.Email), emailError));
}
var items = dto.Items ?? [];
if (items.Count is 0 or > Order.MaxItems)
{
list.Add(new(nameof(dto.Items),
$"Between 1 and {Order.MaxItems} items required."));
}
for (int i = 0; i < items.Count; i++)
{
if (string.IsNullOrWhiteSpace(items[i].Sku))
{
list.Add(new($"Items[{i}].Sku", "SKU is required."));
}
if (items[i].Quantity <= 0)
{
list.Add(new($"Items[{i}].Quantity",
"Quantity must be positive."));
}
}
errors = list;
if (list.Count > 0 || email is null)
{
return false;
}
order = new Order(email);
foreach (var item in items)
{
order.AddItem(item.Sku!, item.Quantity);
}
return true;
}
}
How it works
The DTO, NewOrderDto, is a dumb bag of nullable data, because that is what arrives over the wire. NewOrderMapper.TryMap is the boundary. It checks everything, collects every problem with a path the caller can use, and only builds the domain object when the input is clean. A web endpoint turns the error list into a 400 response; a file importer writes it to a rejects file with the line number.
EmailAddress is a value object. Its constructor is private, so the only way to get one is through TryCreate, and every EmailAddress in the system is known to be valid. Methods that take an EmailAddress never check it again. MailAddress.TryCreate (added in .NET 5) does the parsing, and the extra comparison rejects inputs like "Name <a@example.com>" that parse but are not a bare address.
Order protects its own rules. There are no public setters. Items are added through AddItem, which refuses changes after submission and enforces the item limit. These checks throw, because by the time code calls AddItem with a bad quantity, the boundary has already failed to do its job. That is a bug, not a user mistake, and it should be loud.
Notice that Order.MaxItems is used by the boundary check too. The rule is defined once, in the domain, and the boundary reads it. That is how the two layers stay in sync without copying numbers around.
Variations and pitfalls
- Exceptions or results inside the domain. I throw for broken invariants and reserve result types for outcomes the caller is expected to handle, such as "credit limit exceeded." Chapter 5 has a small
Resulttype for that second case. - Persistence. EF Core can map private setters and backing fields, so a protected entity does not stop you from saving it. Configure the
_itemsfield withHasFieldorUsePropertyAccessMode. - The database is the last boundary.
NOT NULL,CHECKconstraints and unique indexes catch whatever the application misses, including scripts run by hand at 2 A.M. Keep them, even when the C# rules look complete. - Don't over-model. A value object per field is too many. Make one for values that have rules and travel widely: e-mail addresses, money, account numbers, date ranges.