Artykuł · Specyfikacja (Specification) · Kompozyt
Specyfikacja: reguły biznesowe jako obiekty, które się składa
Wzorzec Specyfikacja z Domain-Driven Design: nazwane reguły z isSatisfiedBy, łączenie przez and, or i not, ta sama reguła do walidacji i zapytań, tłumaczenie na SQL przez drzewa wyrażeń, Criteria API i Q. Kod w C#, TypeScript, Javie, Go i Pythonie.
Hurtownia sprzedaje firmom na kredyt kupiecki: płatność 30 dni po dostawie. Reguła „kto może kupić z odroczonym terminem” brzmi prosto – zweryfikowana firma, bez przeterminowanych faktur, co najmniej sześć zamówień w ostatnim roku – ale żyje w czterech miejscach: w koszyku, w panelu handlowca, w zapytaniu do kampanii mailowej i w raporcie dla działu finansów. Każda kopia jest odrobinę inna. Specyfikacja (ang. Specification) robi z takiej reguły obiekt z nazwą z języka domeny, który odpowiada na jedno pytanie: czy ten kandydat ją spełnia?
- 2003
- „Domain-Driven Design” – Eric Evans opisuje Specyfikację wśród wzorców ujawniających ukryte pojęcia
- 3
- zastosowania według Evansa – walidacja, wybór z kolekcji, budowanie obiektów na zamówienie
- 3
- kombinatory – and, or, not – i żadnych nowych metod w repozytorium
Problem: reguła rozsiana po kodzie
Tak wyglądała reguła kredytu kupieckiego po dwóch latach rozwoju:
// checkout
function canBuyOnCredit(c: Customer): boolean {
return c.verified && c.taxId != null && c.overdueInvoices === 0 && c.ordersLastYear >= 6;
}
// e-mail campaign – copied, but someone "simplified" it and the SQL drifted away from the code above
const audience = await db.query(
"SELECT * FROM customers WHERE verified = true AND orders_last_year >= 5", // taxId? overdue invoices?
);
// sales panel – yet another variant, with an extra exception nobody remembers
const eligible = customers.filter((c) => (c.verified || c.vip) && c.overdueInvoices === 0);Trzy kopie, trzy różne odpowiedzi na to samo pytanie biznesowe. Kiedy dział finansów podniesie próg do ośmiu zamówień, ktoś zmieni jedno miejsce z trzech. Do tego reguła nie ma nazwy – w kodzie widać warunki, ale nie widać pojęcia „klient uprawniony do kredytu kupieckiego”.
Rozwiązanie: nazwane reguły i kombinatory
Każdy warunek staje się osobną specyfikacją: VerifiedCompany, HasOverdueInvoices, RegularBuyer. Wspólny interfejs ma metodę isSatisfiedBy oraz kombinatory, które zwracają nowe specyfikacje. Polityka kredytowa to po prostu złożenie: VerifiedCompany and not HasOverdueInvoices and RegularBuyer. Koszyk pyta o jednego klienta, kampania – o wszystkich, ale obie korzystają z tego samego obiektu.
| Rola | Odpowiedzialność | W przykładzie |
|---|---|---|
| Specyfikacja | interfejs: isSatisfiedBy + kombinatory | Specification<T> |
| Specyfikacja liściowa | jedna reguła biznesowa z nazwą | VerifiedCompany, HasOverdueInvoices |
| Kombinator | łączy specyfikacje logicznie, sam też jest specyfikacją | And, Or, Not |
| Klient | używa specyfikacji do walidacji, wyboru lub budowania | koszyk, repozytorium, kampania |
Implementacja w pięciu językach
Wersja C# opiera specyfikację na drzewie wyrażeń (Expression<Func<T, bool>>), więc EF Core przetłumaczy ją na SQL. TypeScript i Go pokazują styl funkcyjny z nazwami reguł, dzięki którym da się powiedzieć klientowi, dlaczego odmówiono. Java korzysta z gotowej Specification<T> ze Spring Data JPA, a Python – z przeciążonych operatorów i obiektów Q/Exists z Django.
Polityka kredytu kupieckiego
// A specification wraps an expression tree, so EF Core can translate it to SQL.
public abstract class Specification<T>
{
private Func<T, bool>? _compiled;
public abstract Expression<Func<T, bool>> ToExpression();
// In memory: compile once and reuse – compiling on every call is expensive.
public bool IsSatisfiedBy(T candidate) => (_compiled ??= ToExpression().Compile())(candidate);
public Specification<T> And(Specification<T> other) => new Binary(this, other, Expression.AndAlso);
public Specification<T> Or(Specification<T> other) => new Binary(this, other, Expression.OrElse);
public Specification<T> Not() => new Negation(this);
private sealed class Binary(Specification<T> left, Specification<T> right,
Func<Expression, Expression, BinaryExpression> combine) : Specification<T>
{
public override Expression<Func<T, bool>> ToExpression()
{
var l = left.ToExpression();
var r = right.ToExpression();
var rightBody = new SwapParameter(r.Parameters[0], l.Parameters[0]).Visit(r.Body); // x => l(x) && r(x)
return Expression.Lambda<Func<T, bool>>(combine(l.Body, rightBody), l.Parameters);
}
}
private sealed class Negation(Specification<T> inner) : Specification<T>
{
public override Expression<Func<T, bool>> ToExpression()
{
var e = inner.ToExpression();
return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body), e.Parameters);
}
}
private sealed class SwapParameter(ParameterExpression from, ParameterExpression to) : ExpressionVisitor
{
protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : node;
}
}
public sealed class VerifiedCompany : Specification<Customer>
{
public override Expression<Func<Customer, bool>> ToExpression() => c => c.Verified && c.TaxId != null;
}
public sealed class HasOverdueInvoices : Specification<Customer>
{
public override Expression<Func<Customer, bool>> ToExpression() =>
c => c.Invoices.Any(i => !i.Paid && i.DueDate < DateTime.UtcNow);
}
// The same rule validates one customer and selects customers in the database:
// var policy = new VerifiedCompany().And(new HasOverdueInvoices().Not());
// if (!policy.IsSatisfiedBy(customer)) throw new TradeCreditRefused(customer.Id);
// var audience = await db.Customers.Where(policy.ToExpression()).ToListAsync(ct);// A specification is a named predicate; combinators build new specifications from existing ones.
export interface Spec<T> {
readonly name: string;
isSatisfiedBy(candidate: T): boolean;
}
export const spec = <T>(name: string, test: (c: T) => boolean): Spec<T> => ({ name, isSatisfiedBy: test });
export const and = <T>(...specs: Spec<T>[]): Spec<T> =>
spec(specs.map((s) => s.name).join(" AND "), (c) => specs.every((s) => s.isSatisfiedBy(c)));
export const or = <T>(...specs: Spec<T>[]): Spec<T> =>
spec(specs.map((s) => s.name).join(" OR "), (c) => specs.some((s) => s.isSatisfiedBy(c)));
export const not = <T>(s: Spec<T>): Spec<T> => spec(`NOT (${s.name})`, (c) => !s.isSatisfiedBy(c));
/** Names of the rules the candidate fails – ready for an error message or a UI hint. */
export const unmet = <T>(candidate: T, ...specs: Spec<T>[]): string[] =>
specs.filter((s) => !s.isSatisfiedBy(candidate)).map((s) => s.name);
interface Customer {
verified: boolean;
taxId?: string;
overdueInvoices: number;
ordersLastYear: number;
}
export const verifiedCompany = spec<Customer>("verified company", (c) => c.verified && !!c.taxId);
export const noOverdueInvoices = spec<Customer>("no overdue invoices", (c) => c.overdueInvoices === 0);
export const regularBuyer = spec<Customer>("6+ orders last year", (c) => c.ordersLastYear >= 6);
const creditRules = [verifiedCompany, noOverdueInvoices, regularBuyer];
export const tradeCreditPolicy = and(...creditRules);
export function assertTradeCredit(customer: Customer): void {
const missing = unmet(customer, ...creditRules); // validation with a reason
if (missing.length) throw new Error(`Trade credit refused: ${missing.join(", ")}`);
}
export const creditAudience = (all: Customer[]) => all.filter((c) => tradeCreditPolicy.isSatisfiedBy(c)); // selection// Spring Data JPA: a Specification<T> builds a Criteria API predicate, the repository runs it as SQL.
public final class CustomerSpecs {
private CustomerSpecs() {}
public static Specification<Customer> verifiedCompany() {
return (root, query, cb) -> cb.and(
cb.isTrue(root.<Boolean>get("verified")),
cb.isNotNull(root.get("taxId")));
}
public static Specification<Customer> hasOverdueInvoices(LocalDate today) {
return (root, query, cb) -> {
Subquery<Long> overdue = query.subquery(Long.class);
Root<Invoice> invoice = overdue.from(Invoice.class);
overdue.select(cb.literal(1L)).where(
cb.equal(invoice.get("customer"), root),
cb.isFalse(invoice.<Boolean>get("paid")),
cb.lessThan(invoice.<LocalDate>get("dueDate"), today));
return cb.exists(overdue);
};
}
public static Specification<Customer> placedAtLeast(int orders) {
return (root, query, cb) -> cb.greaterThanOrEqualTo(root.<Integer>get("ordersLastYear"), orders);
}
}
public interface CustomerRepository extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {}
@Service
class TradeCreditService {
private final CustomerRepository customers;
private final Clock clock;
TradeCreditService(CustomerRepository customers, Clock clock) {
this.customers = customers;
this.clock = clock;
}
List<Customer> creditAudience() {
Specification<Customer> policy = CustomerSpecs.verifiedCompany()
.and(Specification.not(CustomerSpecs.hasOverdueInvoices(LocalDate.now(clock))))
.and(CustomerSpecs.placedAtLeast(6));
return customers.findAll(policy); // one SQL query with EXISTS, nothing filtered in memory
}
}package credit
import "strings"
// Spec is a named business rule; generics (Go 1.18+) make the combinators reusable for any type.
type Spec[T any] struct {
Name string
Test func(T) bool
}
func (s Spec[T]) IsSatisfiedBy(c T) bool { return s.Test(c) }
func And[T any](specs ...Spec[T]) Spec[T] {
names := make([]string, len(specs))
for i, s := range specs {
names[i] = s.Name
}
return Spec[T]{Name: strings.Join(names, " AND "), Test: func(c T) bool {
for _, s := range specs {
if !s.Test(c) {
return false // short-circuit like &&
}
}
return true
}}
}
func Not[T any](s Spec[T]) Spec[T] {
return Spec[T]{Name: "NOT (" + s.Name + ")", Test: func(c T) bool { return !s.Test(c) }}
}
// Unmet returns the names of the rules the candidate fails – handy for error messages.
func Unmet[T any](c T, specs ...Spec[T]) []string {
var failed []string
for _, s := range specs {
if !s.Test(c) {
failed = append(failed, s.Name)
}
}
return failed
}
type Customer struct {
Verified bool
TaxID string
OverdueInvoices int
OrdersLastYear int
}
var (
VerifiedCompany = Spec[Customer]{"verified company", func(c Customer) bool { return c.Verified && c.TaxID != "" }}
NoOverdueInvoices = Spec[Customer]{"no overdue invoices", func(c Customer) bool { return c.OverdueInvoices == 0 }}
RegularBuyer = Spec[Customer]{"6+ orders last year", func(c Customer) bool { return c.OrdersLastYear >= 6 }}
TradeCreditPolicy = And(VerifiedCompany, NoOverdueInvoices, RegularBuyer)
)from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, TypeVar
T = TypeVar("T")
@dataclass(frozen=True)
class Spec(Generic[T]):
"""A named business rule; &, | and ~ build new specifications."""
name: str
test: Callable[[T], bool]
def is_satisfied_by(self, candidate: T) -> bool:
return self.test(candidate)
def __and__(self, other: Spec[T]) -> Spec[T]:
return Spec(f"{self.name} AND {other.name}", lambda c: self.test(c) and other.test(c))
def __or__(self, other: Spec[T]) -> Spec[T]:
return Spec(f"{self.name} OR {other.name}", lambda c: self.test(c) or other.test(c))
def __invert__(self) -> Spec[T]:
return Spec(f"NOT ({self.name})", lambda c: not self.test(c))
@dataclass
class Customer:
verified: bool
tax_id: str | None
overdue_invoices: int
orders_last_year: int
verified_company = Spec[Customer]("verified company", lambda c: c.verified and c.tax_id is not None)
no_overdue_invoices = Spec[Customer]("no overdue invoices", lambda c: c.overdue_invoices == 0)
regular_buyer = Spec[Customer]("6+ orders last year", lambda c: c.orders_last_year >= 6)
trade_credit_policy = verified_company & no_overdue_invoices & regular_buyer
# Django ORM: Q and Exists are specifications the ORM translates to SQL.
# overdue = Invoice.objects.filter(customer=OuterRef("pk"), paid=False, due_date__lt=today)
# audience = Customer.objects.filter(Q(verified=True, tax_id__isnull=False, orders_last_year__gte=6), ~Exists(overdue))Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok po kroku
- Kiedy stosować, a kiedy nie
- Powiązane wzorce
- W praktyce
- Sprawdź się
- Zadanie praktyczne