Catalog specifications
Promotion rules as small objects combined with and, or and not – the Specification pattern from DDD, custom rules and catalog search.
The marketing team changes promotion rules every week: "books or games, in stock, up to 50" one week, "electronics, but no accessories" the next. So far every campaign ended with yet another findPromoProducts2() method and an ever longer if. Time for the Specification pattern (Eric Evans and Martin Fowler): every business rule is a separate object with an isSatisfiedBy(candidate) method, and complex conditions are built from small rules combined with and, or and not.
Task
- Combinators in the base class:
and(other),or(other)andnot(). Each returns a new specification that can be combined again – the original rules stay unchanged. andandorshort-circuit like&&and||: the right rule is not evaluated when the left one already decides the result.- Rules:
InStock(stock greater than zero),PriceAtMost(max)(price not greater thanmax),InCategory(category)(exactly that category). - Catalog:
Catalog.find(spec)returns the products satisfying the specification in catalog order, andcount(spec)returns how many there are. Changing the list passed to the constructor or the returned result must not change the catalog.
A sample promotion: InCategory('books').or(InCategory('games')).and(InStock()).and(PriceAtMost(50)) – in the test data only "Clean Code" and "Catan" satisfy it.
Combinators per language:
- TypeScript / JavaScript – methods
a.and(b),a.or(b),a.not()inCompositeSpecification; the tests add their own rule as a subclass. - Python – methods
and_,or_,not_inSpecification(the&,|and~operators are already there and use them). - C# –
And,Or,Notin the abstractSpecification<T>, acceptingISpecification<T>. - Java – default methods of the
Specification<T>interface; it has one abstract method, so the tests also create rules with lambdas. - Go – functions
And(a, b),Or(a, b),Not(a)plus theSpecFunctype that turns a plain function into a specification.
Topics: Specification
Related articles
- Specification: business rules as objects you can combine
The Specification pattern from Domain-Driven Design: named rules with isSatisfiedBy, combining with and, or and not, one rule for validation and querying, translation to SQL via expression trees, the Criteria API and Q objects. Code in…