Pure domain functions
A pure function takes input and returns output with no side effects. No database calls, no HTTP requests, no reading files. Given the same input, it always returns the same output. That is the definition, and it is the most important tool in this module.
import { CreateOrderInput, OrderEntity } from './order.types';
export function createNewOrder(input: CreateOrderInput): OrderEntity {
return {
userId: input.userId,
bookId: input.bookId,
quantity: input.quantity,
status: 'pending', // business rule: new orders are always pending
};
}
export function markOrderCompleted(order: OrderEntity): OrderEntity {
if (order.status !== 'pending') {
throw new Error(
'Domain Rule Violation: Cannot complete an order in status ' + order.status,
);
}
return { ...order, status: 'completed' };
}Pure functions for creating and transitioning an order entity. No imports from db or queue.
The win is testability. createNewOrder can be tested with one line: expect(createNewOrder(input).status).toBe('pending'). No database, no mock, no setup. markOrderCompleted can be tested the same way. You get hundreds of tests that run in milliseconds, and you catch regressions the moment a business rule slips.
Notice there are no classes. In functional DDD, entities are plain types plus pure functions that transform them. Classes mix data and behavior, which makes them harder to serialize, test, and compose. Plain data with pure functions gives you the same modeling power without the ceremony.
Quiz: Quiz
Loading practice…