Polski

Catalog specifications

Promotion rules as small objects combined with and, or and not – the Specification pattern from DDD, custom rules and catalog search.

medium · typescript · javascript · python · csharp · java · go · 20 XP

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

  1. Combinators in the base class: and(other), or(other) and not(). Each returns a new specification that can be combined again – the original rules stay unchanged.
  2. and and or short-circuit like && and ||: the right rule is not evaluated when the left one already decides the result.
  3. Rules: InStock (stock greater than zero), PriceAtMost(max) (price not greater than max), InCategory(category) (exactly that category).
  4. Catalog: Catalog.find(spec) returns the products satisfying the specification in catalog order, and count(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() in CompositeSpecification; the tests add their own rule as a subclass.
  • Python – methods and_, or_, not_ in Specification (the &, | and ~ operators are already there and use them).
  • C# – And, Or, Not in the abstract Specification<T>, accepting ISpecification<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 the SpecFunc type 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…