Design, refactor, analyze, and review code by applying the principles and patterns of tactical domain-driven design. Triggers on: domain modeling, aggregate design, 'entity', 'value object', 'repository', 'bounded context', 'domain event', 'domain service', code touching domain/ directories, rich domain model discussions.
Installation
Mit Codex oder Claude installieren Kopieren Sie diesen Prompt, fügen Sie ihn in Codex, Claude oder einen anderen Assistant ein und lassen Sie die Skill-Seite prüfen und installieren.
Design, refactor, analyze, and review code by applying the principles and patterns of tactical domain-driven design. Triggers on: domain modeling, aggregate design, 'entity', 'value object', 'repository', 'bounded context', 'domain event', 'domain service', code touching domain/ directories, rich domain model discussions.
version
1.0.0
Tactical DDD
Design, refactor, analyze, and review code by applying the principles and patterns of tactical domain-driven design.
Principles
Isolate domain logic
Use rich domain language
Orchestrate with use cases
Avoid anemic domain model
Separate generic concepts
Make the implicit explicit... like your life depends on it
Design aggregates around invariants
Extract immutable value objects liberally
Repositories are for loading and saving full aggregates
1. Isolate domain logic
What: Domain logic is not mixed with technical code like HTTP and database transactions.
Why: Easier to understand the most important part of the code, easier to validate with domain experts, easier to test and evolve, easier to plan and implement new features.
Test: Could a domain expert read the code? Can the code be unit tested without mocks or spinning up databases?
What: Names in code match exactly what domain experts say. No programmer jargon. No generic names.
Why: Translation between code-speak and business-speak causes bugs. When a domain expert says "assess a claim" and the code says "ProcessEntity", someone will misunderstand something.
Test: Would a domain expert recognize this name? If you'd need to translate it for them, it's wrong.
Common generic terms to watch for:
Manager, Handler, Processor, Helper, Util
Data, Info, Item (when domain terms exist)
Process, Handle, Execute (what does it actually DO?)
// ❌ WRONG - programmer jargonpublicclassClaimHandler
{
public ProcessingResult ProcessClaimData(ClaimDto claimData)
=> _claimProcessor.Handle(claimData);
}
// ✅ RIGHT - domain language
[DddDomainService]
publicclassClaimAssessor
{
public AssessmentDecision AssessClaim(InsuranceClaim claim)
{
if (claim.ExceedsCoverageLimit())
return AssessmentDecision.Deny(DenialReason.ExceedsCoverage);
return AssessmentDecision.Approve();
}
}
3. Orchestrate with use cases
What: A use case is a user goal—something a user would recognize as an action they can perform in your application.
Why: Use cases define the entry points to your domain. They answer "what can a user do?" If something isn't a user goal, it's supporting machinery that belongs elsewhere.
Test (the menu test): If you described your application's features to a user like a menu, would this be on it?
DELIVERY APP MENU:
├── Request Delivery ← Use case: user goal
├── Track Delivery ← Use case: user goal
├── Cancel Delivery ← Use case: user goal
├── Calculate ETA ← NOT a use case: internal machinery
└── Check Delivery Radius ← NOT a use case: domain rule
// ❌ WRONG - not a user goal, this is internal machinery// UseCases/CalculateEta.cspublicasync Task<Duration> CalculateEta(DeliveryId deliveryId)
{
var delivery = await _deliveryRepository.Load(deliveryId);
var driver = await _driverRepository.Load(delivery.DriverId);
return _routeService.EstimateArrival(driver.Location, delivery.Destination);
}
// ✅ RIGHT - actual user goal (appears in menu)// UseCases/CancelDelivery.cspublicasync Task CancelDelivery(DeliveryId deliveryId, CancellationReason reason)
{
var delivery = await _deliveryRepository.Load(deliveryId);
delivery.Cancel(reason);
await _deliveryRepository.Save(delivery);
}
4. Avoid anemic domain model
What: Domain logic lives in domain objects, not in use cases. Use cases orchestrate; domain objects decide.
Why: When business rules leak into use cases, they scatter across the codebase, duplicate, and diverge. The domain becomes a dumb data carrier.
Test: Is your use case making business decisions, or just coordinating? If the use case contains if/else business logic, you likely have an anemic model.
// ❌ WRONG - business logic in use case (anemic domain)publicasync Task ConfirmDropoff(DeliveryId deliveryId, ProofPhoto photo)
{
var delivery = await _deliveryRepository.Load(deliveryId);
// Business rules leaked into use case!if (delivery.Status != DeliveryStatus.InTransit)
thrownew InvalidOperationException("Delivery not in transit");
if (photo isnull && delivery.RequiresSignature)
thrownew InvalidOperationException("Proof of delivery required");
delivery.Status = DeliveryStatus.Delivered;
delivery.ProofPhoto = photo;
delivery.DeliveredAt = DateTime.UtcNow;
await _deliveryRepository.Save(delivery);
}
// ✅ RIGHT - use case orchestrates, domain decidespublicasync Task ConfirmDropoff(DeliveryId deliveryId, ProofPhoto photo)
{
var delivery = await _deliveryRepository.Load(deliveryId);
delivery.ConfirmDropoff(photo); // Domain enforces the rulesawait _deliveryRepository.Save(delivery);
}
Signs of anemic model:
Use cases full of if/else business logic
Domain objects are just data with { get; set; } properties
Business rules duplicated across multiple use cases
Validation logic outside the object being validated
A domain object exposes IsX() + DoX() ("ask, don't tell") instead of a single decision method that both checks and acts
5. Separate generic concepts
What: Generic capabilities that aren't specific to your domain live separately from domain-specific logic.
Why: A retry mechanism, a caching layer, a validation framework—these aren't YOUR domain. Mixing them with domain logic obscures what's actually specific to your business.
Test: Would this code exist in a completely different business domain? If yes, it's generic. If it's specific to YOUR business rules, it's domain.
// ❌ WRONG - generic retry logic mixed with domain// Sales.DeepModel/Delivery/DriverLocator.cs
[DddDomainService]
publicclassDriverLocator
{
// Generic retry logic does not belong in domain!privateasyncTask<T> WithRetry<T>(Func<Task<T>> fn, int attempts)
{
for (var i = 0; i < attempts; i++)
{
try { returnawait fn(); }
catch { if (i == attempts - 1) throw; }
}
thrownew InvalidOperationException("Retry failed");
}
public Task<Driver> FindAvailableDriver(Zone zone)
=> WithRetry(() => SearchDriversInZone(zone), 3);
privateTask<Driver> SearchDriversInZone(Zone zone) { /* domain logic */ }
}
// ✅ RIGHT - same behavior, properly separated// Sales.Adapters/Retry/Retry.cs (generic, reusable anywhere)publicstaticclassRetry
{
publicstaticasyncTask<T> WithAttempts<T>(Func<Task<T>> fn, int attempts)
{
for (var i = 0; i < attempts; i++)
{
try { returnawait fn(); }
catch { if (i == attempts - 1) throw; }
}
thrownew InvalidOperationException("Retry failed");
}
}
// Sales.DeepModel/Delivery/DriverLocator.cs (pure domain, no infra references)
[DddDomainService]
publicclassDriverLocator
{
public Task<Driver> FindAvailableDriver(Zone zone) { /* domain logic */ }
}
// UseCases/DispatchDelivery.cs (orchestrates domain + infra)publicasync Task DispatchDelivery(DeliveryId deliveryId)
{
var delivery = await _deliveryRepository.Load(deliveryId);
var driver = await Retry.WithAttempts(
() => _driverLocator.FindAvailableDriver(delivery.Zone), attempts: 3);
delivery.AssignDriver(driver);
await _deliveryRepository.Save(delivery);
}
6. Make the implicit explicit... like your life depends on it
What: Strive for maximum expressiveness. Go as far as possible to identify and name domain concepts in code. Don't settle for "good enough"—push until the code speaks the domain fluently.
Why: Maximum alignment optimizes communication between engineers and domain experts. Easier to discuss nuances and avoid misconceptions. Easier to plan and implement features and detect when the design of code is causing unnecessary friction.
Test: Could you discuss this code with a domain expert without translation? Are there concepts they use that don't exist in your code?
// This code looks fine - isolated, uses domain termspublicclassDelivery
{
public DeliveryStatus Status { get; privateset; }
public Driver? Driver { get; privateset; }
public DateTime? PickupTime { get; privateset; }
public DateTime? DropoffTime { get; privateset; }
public Photo? ProofOfDelivery { get; privateset; }
publicvoidAssignDriver(Driver driver)
{
if (Status != DeliveryStatus.Confirmed) thrownew InvalidOperationException("...");
Driver = driver;
Status = DeliveryStatus.Assigned;
}
publicvoidRecordPickup()
{
if (Status != DeliveryStatus.Assigned) thrownew InvalidOperationException("...");
PickupTime = DateTime.UtcNow;
Status = DeliveryStatus.InTransit;
}
publicvoidRecordDropoff(Photo photo)
{
if (Status != DeliveryStatus.InTransit) thrownew InvalidOperationException("...");
ProofOfDelivery = photo;
DropoffTime = DateTime.UtcNow;
Status = DeliveryStatus.Delivered;
}
}
// But the TYPES can describe the domain! Each state is a distinct concept.// Reading the types alone tells you how deliveries work.// Modelled as a discriminated union via readonly struct + Kind enum// (the same pattern as Discount in this codebase: see Sources/Sales/Sales.DeepModel/Pricing/Discounts/Discount.cs)
[DddValueObject]
publicreadonlystruct Delivery : IEquatable<Delivery>
{
privatereadonly DeliveryKind _kind;
privatereadonly RequestedDelivery _requested;
privatereadonly ConfirmedDelivery _confirmed;
privatereadonly AssignedDelivery _assigned;
privatereadonly InTransitDelivery _inTransit;
privatereadonly DeliveredDelivery _delivered;
publicstatic Delivery Requested(Customer customer, Restaurant restaurant, IReadOnlyList<MenuItem> items) =>
new(DeliveryKind.Requested, RequestedDelivery.Of(customer, restaurant, items),
default, default, default, default);
public Delivery Confirm(Duration estimatedPrepTime) => _kind switch
{
DeliveryKind.Requested => new(DeliveryKind.Confirmed, default,
ConfirmedDelivery.From(_requested, estimatedPrepTime), default, default, default),
_ => thrownew DomainError($"Cannot confirm delivery in state {_kind}")
};
public Delivery AssignDriver(Driver driver) => _kind switch
{
DeliveryKind.Confirmed => new(DeliveryKind.Assigned, default, default,
AssignedDelivery.From(_confirmed, driver), default, default),
_ => thrownew DomainError($"Cannot assign driver in state {_kind}")
};
// ... RecordPickup, RecordDropoff follow the same patternprivateenum DeliveryKind { Requested, Confirmed, Assigned, InTransit, Delivered }
}
// Each state is a value object holding ONLY the fields guaranteed at that state:
[DddValueObject]
publicreadonlyrecordstructRequestedDelivery(
Customer Customer, Restaurant Restaurant, IReadOnlyList<MenuItem> Items)
{
publicstatic RequestedDelivery Of(Customer c, Restaurant r, IReadOnlyList<MenuItem> i) => new(c, r, i);
}
[DddValueObject]
publicreadonlyrecordstructAssignedDelivery(
Customer Customer, Restaurant Restaurant, IReadOnlyList<MenuItem> Items,
Driver Driver, // Now guaranteed non-null
DateTime EstimatedPickup)
{
publicstatic AssignedDelivery From(ConfirmedDelivery prev, Driver driver) => new(
prev.Customer, prev.Restaurant, prev.Items, driver, DateTime.UtcNow.AddMinutes(15));
}
[DddValueObject]
publicreadonlyrecordstructDeliveredDelivery(
Customer Customer, Restaurant Restaurant, IReadOnlyList<MenuItem> Items,
Driver Driver,
DateTime PickupTime,
DateTime DropoffTime, // Now guaranteed non-null
Photo ProofOfDelivery); // Now guaranteed non-null
Smaller improvements matter too:
// Extract an if statement to a named methodif (distance.Kilometers > 10 && !driver.HasLongRangeVehicle) { ... }
if (delivery.ExceedsDriverRange(driver)) { ... }
// Name a boolean expressionvar canAssign = driver.IsAvailable && driver.IsInZone(delivery.Zone) && !driver.AtCapacity;
var canAssign = driver.CanAccept(delivery);
// Rename to use domain languagevar fee = customFee ?? standardFee;
var fee = customFee ?? defaultDeliveryFee;
Ways to increase expressiveness:
Model states as distinct types (Delivery with Status enum → RequestedDelivery, ConfirmedDelivery, etc. via the readonly-struct discriminated-union pattern this codebase already uses for Discount)
Make optional fields guaranteed at the right state (Driver? → Driver non-null in AssignedDelivery)
Extract conditionals to named methods (complex if → ExceedsDriverRange)
Rename variables to use domain language (standardFee → defaultDeliveryFee)
7. Design aggregates around invariants
What: An aggregate is a cluster of objects that must be consistent together. The aggregate root enforces the rules. External code cannot violate invariants.
Why: Without clear boundaries, inconsistent states creep in. One piece of code updates the delivery, another updates the route, and suddenly the ETA is wrong.
Test: What must be true at all times? What rules must never be broken? The objects involved in those rules form an aggregate.
// ❌ WRONG - no aggregate boundary, invariants violatedpublicclassDelivery
{
public List<DeliveryStop> Stops { get; set; } // Exposed!public Distance TotalDistance { get; set; }
}
// External code can break invariants
delivery.Stops.Add(new DeliveryStop(location));
// Oops - TotalDistance is now wrong!// ✅ RIGHT - aggregate protects invariants
[DddAggregateRoot]
publicclassDelivery
{
privatereadonly List<DeliveryStop> _stops = new();
private Distance _totalDistance = Distance.Zero();
public DeliveryStatus Status { get; privateset; }
public IReadOnlyList<DeliveryStop> Stops => _stops;
public Distance TotalDistance => _totalDistance;
publicvoidAddStop(Location location)
{
if (Status != DeliveryStatus.Planning)
thrownew DeliveryNotModifiableError(_id);
var previousStop = _stops[^1];
var stop = new DeliveryStop(location);
_stops.Add(stop);
_totalDistance = _totalDistance.Add(
previousStop.DistanceTo(location)); // Invariant maintained!
}
publicvoidRemoveStop(StopId stopId)
{
if (_stops.Count <= 2)
thrownew MinimumStopsRequiredError(_id);
_stops.RemoveAll(s => s.Id.Equals(stopId));
_totalDistance = CalculateTotalDistance(); // Invariant maintained!
}
}
Aggregate rules:
One root entity per aggregate
External code accesses only through the root
The root enforces all invariants
Reference other aggregates by ID, not object
Methods should operate on the same state—if they don't, split the aggregate
8. Extract immutable value objects liberally
What: When something is defined by its attributes (not identity), make it an immutable value object. Do this liberally—more value objects is usually better.
Why: Value objects are simple. They can't change unexpectedly. They're easy to test. They make domain concepts explicit. They're also a good way to extract logic from aggregates and entities that can easily get large—keep entities focused by pulling cohesive concepts into value objects.
Test: Does this need a unique ID to track it over time? No? It's probably a value object.
// Entity with primitives that should be a value objectpublicclassDelivery
{
public DeliveryId Id { get; }
publicdecimal FeeAmount { get; privateset; }
publicstring FeeCurrency { get; privateset; }
}
// Extract the value objectpublicclassDelivery
{
public DeliveryId Id { get; }
public Money Fee { get; privateset; }
}
// Idiomatic C# value object in this codebase:// readonly struct, IEquatable<T>, static factory, validating ctor, override Equals/GetHashCode.// (See Sources/Sales/Sales.Commons/Money.cs and PercentageDiscount.cs for the canonical shape.)
[DddValueObject]
publicreadonlystruct Money : IEquatable<Money>
{
publicdecimal Amount { get; }
public Currency Currency { get; }
publicstatic Money Of(decimal amount, Currency currency) => new(amount, currency);
privateMoney(decimal amount, Currency currency)
{
if (amount < 0) thrownew DomainError("Money amount cannot be negative");
Amount = amount;
Currency = currency;
}
public Money Add(Money other)
{
if (Currency != other.Currency)
thrownew CurrencyMismatchError(Currency, other.Currency);
returnnew Money(Amount + other.Amount, Currency);
}
publicboolEquals(Money other) => Amount == other.Amount && Currency == other.Currency;
publicoverrideboolEquals(object? obj) => obj is Money other && Equals(other);
publicoverrideintGetHashCode() => HashCode.Combine(Amount, Currency);
publicoverridestringToString() => $"{Amount}{Currency}";
}
Good candidates for value objects:
Money, Currency, Percentage
DateRange, TimeSlot, Duration
Address, Coordinates, Distance
EmailAddress, PhoneNumber, Url
Quantity, Weight, Temperature, Precipitation
PersonName, CompanyName
9. Repositories are for loading and saving full aggregates
The job of a repository is to load and save entire aggregates - not partial aggregates or nested entities inside an aggregate. The Load method takes an ID and returns the full aggregate.
A repository should not exist for a domain object that is not an aggregate. An entity that is part of an aggregate → does not have a repository. It is loaded via the aggregate root's repository.
The Hydrate method is used ONLY for constructing an aggregate from its persisted state. It should not be abused for other use cases like creating new instances. Each creation flow should have a dedicated factory method, e.g. Order.FromExisting(), Order.New(), Order.Draft().
The Save method of a repository should take the full aggregate.
If you just want to query information to display without modifying state and applying business rules, create a separate read model object and don't use a repository.
// ✅ RIGHT - repository for an aggregate root, factory methods for each creation scenariopublicinterfaceIDeliveryRepository
{
Task<Delivery> Load(DeliveryId id);
Task Save(Delivery delivery);
}
publicclassDelivery
{
// Hydration: reconstruct from persistence — DO NOT use for new instancespublicstatic Delivery Hydrate(DeliveryId id, DeliveryStatus status, IReadOnlyList<DeliveryStop> stops,
Distance totalDistance) => new(id, status, stops, totalDistance);
// Creation factories — one per use case:publicstatic Delivery Draft(Customer customer) => new(DeliveryId.New(), DeliveryStatus.Draft,
new List<DeliveryStop>(), Distance.Zero());
publicstatic Delivery FromQuote(Quote quote) => new(DeliveryId.New(), DeliveryStatus.Planning,
quote.Stops, quote.TotalDistance);
}
Mandatory Checklist
When designing, refactoring, analyzing, or reviewing code:
Verify domain is isolated from infrastructure (no DB/HTTP/logging in domain; generic utilities in infra; domain doesn't using infra)
Verify names are from YOUR domain, not generic developer jargon (Manager, Handler, Data, Process)
Verify use cases are intentions of users, human or automated (apply the menu test)
Verify business logic lives in domain objects, use cases only orchestrate. No IsApplicable() + Apply() split — give the domain object one decision method that both checks and acts
Verify states are modeled as distinct types where appropriate (readonly-struct discriminated unions; see Discount in this codebase)
Verify hidden domain concepts are extracted and named explicitly (a decimal precipitation should usually become a Precipitation value object)
Verify aggregates are designed around invariants, not naive mapping of domain nouns
Verify values are extracted into value objects expressing a domain concept (readonly struct, IEquatable<T>, static Of(...) factory, validating private ctor, override Equals/GetHashCode/ToString)
Verify no abuse of hydrate methods for creation scenarios. Each creation scenario must have a dedicated factory method (Of, New, Draft, FromExisting, ...)