Especificación
Escrito por Darjus Kazakevic · revisado el
One named rule instead of three copies of an if.
The same rule, such as "an invoice is overdue", often appears three times: in validation, in a database query, and in a filter over a list. Written three times, the copies drift apart. A Specification writes the rule once, as an object with one method: isSatisfiedBy(candidate).
Because rules are objects, they combine: overdue.and(highValue) is a new rule. The main cost is turning rules into efficient SQL, which is hard to do well.
En esencia — Write a business rule once, as an object you can combine with and, or and not, then reuse it for validation, filtering and queries.
Cuándo recurrir a él
Recurre a él cuando
- The same rule appears in validation, queries and UI code
- Rules combine: overdue, and high value, and not disputed
- A repository is growing many findByXAndY methods
Reconsidéralo cuando
- A one-off condition: an inline filter is clearer
- Rules that never combine and live in one place
- When it turns into a second query language next to your ORM
The parts
- isSatisfiedBy
- The one method of the pattern: given a candidate, return true or false. It is a pure function, so you can test the rule on its own.
- Composition
- and, or and not each return a new specification. Complex rules are built from small named ones, and the result reads like a sentence.
- One rule, three uses
- The same object validates one candidate, filters a list in memory, and, with a translator, becomes a WHERE clause. The rule never forks into copies.
- Named business rules
- Each specification has a business name, such as PremiumCustomer or EligibleForRefund. You can search for the rule by name instead of reading inline if statements.
Reglas de diseño
- Name each spec in business words
- OverdueInvoice, not DueDateBeforeTodayAndUnpaid. The name documents the rule, and it lets people find every place the rule applies.
- Keep specs pure
- isSatisfiedBy must not load data or call services. Pass in what it needs, such as today's date, through the constructor, so the result is the same in tests and in production.
- Translate to the query; do not load everything
- A spec that only runs in memory forces you to load every row and filter in code. For large tables, give the spec a SQL or criteria form that the repository uses.
Errores habituales
- Specs that only run in memory, so the repository loads the whole table to return 50 rows.
- Building a full query language on top of the ORM, with fewer features than the ORM.
- A spec that reads the clock or the database itself, so a test passes today and fails tomorrow.