Software Architecture

Domain-Driven Design: Domain Services, business logic that does not belong to an Entity

Learn to recognize an operation that needs a Domain Service and distinguish it from coordination and technical integrations. Design shipping selection in TypeScript, preserve Entities' own rules, and verify your decisions with tests and criteria for reviewing AI-generated code.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

A store needs to choose a carrier. The cheapest option may not cover the destination, accept the package's weight, or meet the promised deadline. The decision depends on the shipment and several offers; no individual offer can know whether it is the best alternative.

The first implementation ends up in ShippingService: it queries providers, filters options, assigns a carrier, saves the shipment, and returns HTTP. When the team wants to test the selection rule, it discovers it needs to simulate the entire operation.

There is a business decision here that deserves its own name. There are also coordination and communication tasks that must be distinguished from it. A Domain Service expresses the former without turning the entire operation into a class that does everything.

What makes a service a Domain Service

A Domain Service represents a meaningful business operation that does not naturally fit as the responsibility of an Entity or a Value Object. Its interface uses model concepts, and the service retains no state belonging to an operation between calls. These criteria come from the Services section of Eric Evans's DDD reference.

It does not mean “any class ending in Service.” Nor is a function receiving two objects enough: adding two monetary amounts can remain behavior of Money.

The useful question is: who can own this decision without distorting their responsibility?

In shipping selection, Shipment knows its characteristics and controls whether it can accept an assignment. Each offer describes a possibility. Comparing alternatives using commercial priorities can be expressed as ShippingOptionSelector.

That name identifies a specific decision. ShippingManager, by contrast, does not reveal whether it selects options, prints labels, or records incidents.

Domain, Application, and Infrastructure: three distinct responsibilities

An Application Service implements or coordinates a Use Case, an operation offered by the application: it obtains the necessary information, invokes the model, and organizes saving or subsequent effects. It should not duplicate rules belonging to the Domain.

An Infrastructure Service handles a technical mechanism: querying a shipping API, sending an email, or accessing storage. It may interpret protocols and translate formats, but that does not automatically make its decisions business rules.

A Domain Service answers a model question: given these characteristics and these valid alternatives, which should we choose?

The distinction can be read as follows:

Application: obtain offers, request a selection, and coordinate assignment.
Domain Service: choose by coverage, weight, deadline, and commercial priority.
Entity: accept or reject assignment according to its state.
Infrastructure: query the provider and validate its technical response.

Fowler describes the coordination of application operations in his Service Layer pattern. That separation helps distinguish responsibilities, although “service” is used with different meanings in each architecture.

Before: one function mixes mechanisms and decisions

This partial snippet uses fictional collaborators: carrierApi queries offers and shipmentStore saves the assignment. It is not an executable endpoint:

async function processShipment(req, res) {
  const offers = await carrierApi.getOffers(req.body.shipmentId);
  const selected = offers
    .filter(offer => offer.priceMinorUnits >= 0)
    .sort((a, b) => a.priceMinorUnits - b.priceMinorUnits)[0];
  await shipmentStore.assignCarrier(req.body.shipmentId, selected.carrierId);
  res.json({ carrierId: selected.carrierId });
}

Besides mixing responsibilities, the criterion is insufficient: the cheapest offer could fail weight, zone, or deadline requirements, and there may be no offers at all. Moving the entire block into domain/shipping.service.ts would preserve both problems.

Improvement requires two different steps: agreeing on the correct rule and placing each responsibility. A folder structure does not decide which offer fulfills a commercial promise.

Complete example: choosing a shipping offer

Rules and boundaries of the case

For this store, we will choose the lowest-priced offer among those that:

  • Cover exactly the shipment's zone.
  • Accept its weight, including the advertised maximum limit.
  • Have a transit time less than or equal to the requested maximum.

If two offers cost the same, the carrier identifier appearing first in JavaScript string comparison wins. This is an instructional, deterministic tie-breaking rule. If no compatible options exist, the result expresses that no selection is available.

All amounts are in EUR cents. Times are whole transit days, without calendars, holidays, or pickup schedules. We do not evaluate instantaneous capacity or guarantee an offer remains valid after selection.

We will use a minimal Value Object, Weight, and an Entity, Shipment. They implement only what is needed to collaborate with the service. Offers are known input structures validated by whoever obtains them; the example is not an external-response parser.

Self-contained program

Save this block as domain-service.ts and run it with node domain-service.ts using Node.js 24.21.0. No external packages are required. Direct execution removes TypeScript annotations through type stripping, but does not perform static type checking.

import assert from 'node:assert/strict';

type Zone = 'local' | 'regional';

class Weight {
  readonly grams: number;

  constructor(grams: number) {
    if (!Number.isSafeInteger(grams) || grams <= 0) {
      throw new Error('El peso debe ser un entero positivo de gramos');
    }
    this.grams = grams;
    Object.freeze(this);
  }
}

class Shipment {
  #id: string;
  #weight: Weight;
  #zone: Zone;
  #carrierId: string | null = null;

  constructor(id: string, weight: Weight, zone: Zone) {
    if (!id.trim()) throw new Error('El envío necesita un identificador');
    this.#id = id;
    this.#weight = weight;
    this.#zone = zone;
  }

  get id(): string { return this.#id; }
  get weight(): Weight { return this.#weight; }
  get zone(): Zone { return this.#zone; }
  get carrierId(): string | null { return this.#carrierId; }

  assignCarrier(carrierId: string): void {
    if (this.#carrierId !== null) throw new Error('El envío ya tiene transportista');
    if (!carrierId.trim()) throw new Error('El transportista necesita identidad');
    this.#carrierId = carrierId;
  }
}

type ShippingOffer = Readonly<{
  carrierId: string;
  zone: Zone;
  maxWeightGrams: number;
  transitDays: number;
  priceMinorUnits: number;
}>;

type Selection =
  | { kind: 'unavailable' }
  | { kind: 'selected'; carrierId: string; priceMinorUnits: number };

class ShippingOptionSelector {
  select(
    shipment: Shipment,
    offers: readonly ShippingOffer[],
    maxTransitDays: number,
  ): Selection {
    if (!Number.isSafeInteger(maxTransitDays) || maxTransitDays <= 0) {
      throw new Error('El plazo máximo debe ser un entero positivo');
    }

    const candidates = offers.filter(offer =>
      offer.zone === shipment.zone &&
      offer.maxWeightGrams >= shipment.weight.grams &&
      offer.transitDays <= maxTransitDays);

    candidates.sort((a, b) => {
      if (a.priceMinorUnits !== b.priceMinorUnits) {
        return a.priceMinorUnits < b.priceMinorUnits ? -1 : 1;
      }
      if (a.carrierId === b.carrierId) return 0;
      return a.carrierId < b.carrierId ? -1 : 1;
    });

    const best = candidates[0];
    return best
      ? { kind: 'selected', carrierId: best.carrierId, priceMinorUnits: best.priceMinorUnits }
      : { kind: 'unavailable' };
  }
}

const offers: ShippingOffer[] = [
  { carrierId: 'cheap-slow', zone: 'local', maxWeightGrams: 5000,
    transitDays: 5, priceMinorUnits: 200 },
  { carrierId: 'small-only', zone: 'local', maxWeightGrams: 1000,
    transitDays: 1, priceMinorUnits: 300 },
  { carrierId: 'regional', zone: 'regional', maxWeightGrams: 5000,
    transitDays: 1, priceMinorUnits: 350 },
  { carrierId: 'carrier-b', zone: 'local', maxWeightGrams: 2000,
    transitDays: 2, priceMinorUnits: 500 },
  { carrierId: 'carrier-a', zone: 'local', maxWeightGrams: 2000,
    transitDays: 2, priceMinorUnits: 500 },
];

const shipment = new Shipment('shipment-1', new Weight(2000), 'local');
const selector = new ShippingOptionSelector();
const beforeSelection = JSON.stringify(offers);
const result = selector.select(shipment, offers, 2);

assert.deepEqual(result, {
  kind: 'selected', carrierId: 'carrier-a', priceMinorUnits: 500,
});
assert.equal(shipment.carrierId, null);
assert.equal(JSON.stringify(offers), beforeSelection);
assert.deepEqual(selector.select(shipment, offers, 1), { kind: 'unavailable' });
assert.deepEqual(selector.select(shipment, [], 2), { kind: 'unavailable' });
assert.throws(() => selector.select(shipment, offers, 0), /entero positivo/);

if (result.kind === 'selected') shipment.assignCarrier(result.carrierId);
assert.equal(shipment.carrierId, 'carrier-a');
assert.throws(() => shipment.assignCarrier('carrier-b'), /ya tiene/);
console.log('Selección, límites y responsabilidad de la Entity verificados');

What each collaborator decided

The input is a local shipment weighing 2,000 grams with a maximum of two days. The 200-cent offer misses the deadline; the 300-cent offer cannot accept the weight; the regional offer does not cover the zone. Two 500-cent options remain, and the tie-breaker selects carrier-a.

The Domain Service does not modify the shipment or the original array. filter() produces another array, and sorting applies to that result. Selection returns an explicit decision; it does not initiate external calls.

Afterward, Shipment.assignCarrier() controls its own rule: disallow a second assignment. That Invariant, a condition that must hold after valid operations, remains the Entity's responsibility. The service does not write a public field to bypass it.

The assertions check coverage, weight at the limit, transit time at the limit, tie-breaking, and the absence of alternatives. They also show that selecting and assigning are different operations. The program was run with Node.js 24.21.0 and completed the included assertions. Static TypeScript checking was not performed, and actual carrier availability or persistence was not tested.

Valid offers must contain nonempty identifiers, nonnegative integer prices, positive weights, and accepted transit times. In a real integration, that contract needs runtime validation: Readonly and TypeScript annotations do not validate JSON. If that structure starts needing more behavior of its own, you can introduce another model concept; developing one is unnecessary here.

How an Application Service would use it

The following snippet can be added to the preceding program. It illustrates in-memory coordination and depends on its types; it is not another self-contained project and does not implement persistence:

interface ShippingOfferReader {
  findFor(shipment: Shipment): Promise<readonly ShippingOffer[]>;
}

class AssignShippingOption {
  #reader: ShippingOfferReader;
  #selector: ShippingOptionSelector;

  constructor(reader: ShippingOfferReader, selector: ShippingOptionSelector) {
    this.#reader = reader;
    this.#selector = selector;
  }

  async execute(shipment: Shipment, maxTransitDays: number): Promise<Selection> {
    const offers = await this.#reader.findFor(shipment);
    const result = this.#selector.select(shipment, offers, maxTransitDays);
    if (result.kind === 'selected') shipment.assignCarrier(result.carrierId);
    return result;
  }
}

Dependencies are explicit in the constructor. A ShippingOfferReader implementation can query an HTTP API, validate the response, and translate it. The Use Case decides when to obtain it; the selector decides which alternative meets the policy.

The example already receives the Entity. A real operation would also need to retrieve it and save the change, as well as check permissions. If the query fails, it should not automatically become an empty list: “there are no compatible offers” is not equivalent to “I could not query.”

Nor can you guarantee assignment merely because the selector chose correctly. The offer could change, or two operations could modify the same shipment. You need validity agreements and concurrency mechanisms when integrating and saving; a correct calculation does not replace those guarantees.

Stateless does not mean dependency-free

The selector does not remember the last shipment, candidate list, or result. Each call receives the necessary data. That makes it stateless, meaning there is no operation state that accidentally affects the next one.

It may have stable dependencies, such as a priority policy or immutable configuration. That is not equivalent to saving the previous request's data in instance properties.

Also distinguish statelessness from a pure function. A stateless service can query a collaborator and depend on changing data. Predictable tests require making that collaboration explicit. When reasonable, passing facts already obtained, as we did with offers, keeps the decision separate from the query.

A Domain Service need not be a class. If a function with a business name clearly expresses the operation and its dependencies, it may be enough. The absence of a class ending in Service does not eliminate the Domain responsibility.

Second scenario: a cancellation that should stay in the Entity

A team proposes OrderService.cancel(order) to check that an order has not shipped and then change its state through setters. All the information and the transition belong to the order itself.

In that case, Order.cancel() is a more natural location. The Entity controls whether its state permits cancellation and prevents other entry points from applying a different transition. The Use Case loads the order, requests cancellation, and saves the result.

Extracting the rule just to create a service drains behavior from the Entity. That systematic shift is a sign of the Anemic Domain Model described by Fowler.

Now add a commercial policy comparing several orders in an account to decide which compensation alternatives to offer. That decision could justify a Domain Service, but does not give it permission to modify any order without using its methods.

This scenario teaches us to separate an Entity's own transition from a decision relating several concepts. Counting objects or lines of code does not resolve that choice.

Third scenario: education and a policy that queries history

An academy needs to decide whether someone can request a certification exam. The decision combines certification requirements, passed courses, and a restriction on recent attempts. No individual enrollment contains the complete policy on its own.

A CertificationEligibilityPolicy can evaluate that evidence and return a result with rejection reasons. The Application Service obtains the history and coordinates the request. Infrastructure knows how to query it; it should not invent whether an external course is equivalent to the required prerequisite.

If the evidence belongs to another Bounded Context, the boundary within which another model has consistent meaning, avoid importing its implementations. An Anticorruption Layer, or ACL, can query through HTTP and translate information into a consumer contract.

The policy must distinguish “requirement not met” from “evidence unavailable.” Furthermore, a prior check does not automatically reserve an exam attempt: if concurrent limits exist, they must be protected where the request is recorded. The HTTP query and local save do not form a shared transaction.

Here you learn to separate obtaining knowledge from evaluating it and to recognize the limits of a decision made with a particular read.

How to avoid a God Service

A God Service concentrates too many responsibilities and eventually becomes the place where every change ends up. In shipping, a single class could select options, bill, print labels, and send emails because everything “has to do with shipments.”

A shared topic is insufficient to justify that grouping. Review which rules change together and which questions each operation answers. If changing the email provider requires reviewing shipping selection, the boundaries probably are not helping.

Do not solve it by creating a class for every line either. Start with a recognizable decision: select shipping, evaluate eligibility, or calculate compensation. Keep the behavior belonging to Entities and Value Objects inside them.

A helper formatting a date does not become a Domain Service by being in the domain folder. It must express a model operation, not merely a reusable technical utility.

When a simpler solution is sufficient

If an operation only needs to check local data and change an Entity's state, use its method. If you need to present a list without relevant rules, a simple query can handle it. Do not introduce a Domain Service just to make every request pass through an extra class.

Even a selection can start as a small function. Extracting a service is worthwhile when it names a business decision, concentrates a policy that would otherwise be duplicated, or makes relevant collaborations explicit. Code repetition is one possible signal, not a requirement for that responsibility to exist.

Prompts for directing and reviewing AI-generated code

Decide where a rule belongs

Analyze these shipping and order operations. Classify each decision as Entity or Value Object behavior, Domain Service, Application coordination, or technical integration. Justify this using the information required and who owns the transition. Do not edit files or create services by default. Return doubts and counterexamples. A person will validate commercial policies and model boundaries before accepting the classification.

Implement a bounded policy

Implement ShippingOptionSelector in TypeScript without dependencies. It receives a shipment and already validated offers in EUR cents. Filter by zone, inclusive maximum weight, and inclusive maximum transit time; choose the lowest price and break ties by identifier. Return unavailable if there is no candidate. Do not query HTTP, save data, or modify the Entity. Deliver code and assertions for boundaries, tie-breaking, and no mutation. A person will run the tests and check the meaning of transit time and validity.

Review without emptying the model

Review the diff against the attached rules. Look for Entity rules moved to services, properties containing previous-request data, hidden technical dependencies, and failed queries treated as business rejections. Do not change files. Return evidence and an observable scenario for each finding; flag uncertainties. A person will review concurrency and external effects, which selector tests do not guarantee.

AI generating a small class and passing tests does not demonstrate that the responsibility is correctly placed. Check whether the operation represents a real decision and whether the Entity still protects its changes.

Three exercises with reasoned solutions

1. The cheapest offer takes too long

The AI sorts by price and rejects the first offer if it misses the deadline, without reviewing subsequent ones. What incorrect result could it produce?

Reasoned solution: returning that no options exist even though another, more expensive one meets the requirements. First build the eligible set, then choose within it. A test with a cheap, slow offer and another compatible one protects the decision sequence.

2. A service remembers the last shipment

To avoid passing parameters, the selector stores currentShipment and lastOffers in properties. The same instance serves several operations. What would you change?

Reasoned solution: receive those data in every call and keep candidates and result as local variables. This prevents one operation from depending on information left by another. A stable dependency can remain in the constructor; each selection's own data need not become shared state.

3. Moving Money.add() to a service

A proposal removes Money.add() and creates CalculationService.addMoney(), which compares currencies and adds amounts. What does it contribute?

Reasoned solution: under that description, no new responsibility appears to justify extraction. Compatible addition is natural behavior of Money. A policy deciding how to distribute a discount among several lines could require another location, but does not require removing valid arithmetic from the Value Object.

Criteria for choosing a Domain Service

Look for a business operation with no natural owner among the existing Entities and Value Objects. Define which facts it needs, which decision it returns, and which transitions its collaborators must continue controlling.

Then separate that decision from queries, saving, and protocols. If you can check the policy through explicit inputs and business scenarios, without emptying the rest of the model or hiding dependencies, the service is fulfilling a specific responsibility.

Loading conversation…

Keep learning