Specification pattern
In computer programming, the specification pattern is a particular software design pattern, whereby business rules can be recombined by chaining the business rules together using Boolean logic. The pattern is frequently used in the context of domain-driven design.
A specification pattern outlines a business rule that is combinable with other business rules. In this pattern, a unit of business logic inherits its functionality from the abstract aggregate Composite Specification class. The Composite Specification class has one function called IsSatisfiedBy that returns a Boolean value. After instantiation, the specification is "chained" with other specifications, making new specifications easily maintainable, yet highly customizable business logic. Furthermore, upon instantiation the business logic may, through method invocation or inversion of control, have its state altered in order to become a delegate of other classes such as a persistence repository.
As a consequence of performing runtime composition of high-level business/domain logic, the Specification pattern is a convenient tool for converting ad-hoc user search criteria into low level logic to be processed by repositories.
Since a specification is an encapsulation of logic in a reusable form it is very simple to thoroughly unit test, and when used in this context is also an implementation of the humble object pattern.
Code examples
[edit ]C#
[edit ]publicinterfaceISpecification { boolIsSatisfiedBy(objectcandidate); ISpecificationAnd(ISpecificationother); ISpecificationAndNot(ISpecificationother); ISpecificationOr(ISpecificationother); ISpecificationOrNot(ISpecificationother); ISpecificationNot(); } publicabstractclassCompositeSpecification:ISpecification { publicabstractboolIsSatisfiedBy(objectcandidate); publicISpecificationAnd(ISpecificationother) { returnnewAndSpecification(this,other); } publicISpecificationAndNot(ISpecificationother) { returnnewAndNotSpecification(this,other); } publicISpecificationOr(ISpecificationother) { returnnewOrSpecification(this,other); } publicISpecificationOrNot(ISpecificationother) { returnnewOrNotSpecification(this,other); } publicISpecificationNot() { returnnewNotSpecification(this); } } publicclassAndSpecification:CompositeSpecification { privateISpecification_leftCondition; privateISpecification_rightCondition; publicAndSpecification(ISpecificationleft,ISpecificationright) { _leftCondition=left; _rightCondition=right; } publicoverrideboolIsSatisfiedBy(objectcandidate) { return_leftCondition.IsSatisfiedBy(candidate)&&_rightCondition.IsSatisfiedBy(candidate); } } publicclassAndNotSpecification:CompositeSpecification { privateISpecification_leftCondition; privateISpecification_rightCondition; publicAndNotSpecification(ISpecificationleft,ISpecificationright) { _leftCondition=left; _rightCondition=right; } publicoverrideboolIsSatisfiedBy(objectcandidate) { return_leftCondition.IsSatisfiedBy(candidate)&&_rightCondition.IsSatisfiedBy(candidate)!=true; } } publicclassOrSpecification:CompositeSpecification { privateISpecification_leftCondition; privateISpecification_rightCondition; publicOrSpecification(ISpecificationleft,ISpecificationright) { _leftCondition=left; _rightCondition=right; } publicoverrideboolIsSatisfiedBy(objectcandidate) { return_leftCondition.IsSatisfiedBy(candidate)||_rightCondition.IsSatisfiedBy(candidate); } } publicclassOrNotSpecification:CompositeSpecification { privateISpecification_leftCondition; privateISpecification_rightCondition; publicOrNotSpecification(ISpecificationleft,ISpecificationright) { _leftCondition=left; _rightCondition=right; } publicoverrideboolIsSatisfiedBy(objectcandidate) { return_leftCondition.IsSatisfiedBy(candidate)||_rightCondition.IsSatisfiedBy(candidate)!=true; } } publicclassNotSpecification:CompositeSpecification { privateISpecification_wrapped; publicNotSpecification(ISpecificationx) { _wrapped=x; } publicoverrideboolIsSatisfiedBy(objectcandidate) { return!_wrapped.IsSatisfiedBy(candidate); } }
C# 6.0 with generics
[edit ]publicinterfaceISpecification<T> { boolIsSatisfiedBy(Tcandidate); ISpecification<T>And(ISpecification<T>other); ISpecification<T>AndNot(ISpecification<T>other); ISpecification<T>Or(ISpecification<T>other); ISpecification<T>OrNot(ISpecification<T>other); ISpecification<T>Not(); } publicabstractclassLinqSpecification<T>:CompositeSpecification<T> { publicabstractExpression<Func<T,bool>>AsExpression(); publicoverrideboolIsSatisfiedBy(Tcandidate)=>AsExpression().Compile()(candidate); } publicabstractclassCompositeSpecification<T>:ISpecification<T> { publicabstractboolIsSatisfiedBy(Tcandidate); publicISpecification<T>And(ISpecification<T>other)=>newAndSpecification<T>(this,other); publicISpecification<T>AndNot(ISpecification<T>other)=>newAndNotSpecification<T>(this,other); publicISpecification<T>Or(ISpecification<T>other)=>newOrSpecification<T>(this,other); publicISpecification<T>OrNot(ISpecification<T>other)=>newOrNotSpecification<T>(this,other); publicISpecification<T>Not()=>newNotSpecification<T>(this); } publicclassAndSpecification<T>:CompositeSpecification<T> { privateISpecification<T>_left; privateISpecification<T>_right; publicAndSpecification(ISpecification<T>left,ISpecification<T>right) { _left=left; _right=right; } publicoverrideboolIsSatisfiedBy(Tcandidate)=>_left.IsSatisfiedBy(candidate)&&_right.IsSatisfiedBy(candidate); } publicclassAndNotSpecification<T>:CompositeSpecification<T> { privateISpecification<T>_left; privateISpecification<T>_right; publicAndNotSpecification(ISpecification<T>left,ISpecification<T>right) { _left=left; _right=right; } publicoverrideboolIsSatisfiedBy(Tcandidate)=>_left.IsSatisfiedBy(candidate)&&!_right.IsSatisfiedBy(candidate); } publicclassOrSpecification<T>:CompositeSpecification<T> { privateISpecification<T>_left; privateISpecification<T>_right; publicOrSpecification(ISpecification<T>left,ISpecification<T>right) { _left=left; _right=right; } publicoverrideboolIsSatisfiedBy(Tcandidate)=>_left.IsSatisfiedBy(candidate)||_right.IsSatisfiedBy(candidate); } publicclassOrNotSpecification<T>:CompositeSpecification<T> { privateISpecification<T>_left; privateISpecification<T>_right; publicOrNotSpecification(ISpecification<T>left,ISpecification<T>right) { _left=left; _right=right; } publicoverrideboolIsSatisfiedBy(Tcandidate)=>_left.IsSatisfiedBy(candidate)||!_right.IsSatisfiedBy(candidate); } publicclassNotSpecification<T>:CompositeSpecification<T> { ISpecification<T>other; publicNotSpecification(ISpecification<T>other)=>this.other=other; publicoverrideboolIsSatisfiedBy(Tcandidate)=>!other.IsSatisfiedBy(candidate); }
Python
[edit ]fromabcimport ABC, abstractmethod fromdataclassesimport dataclass fromtypingimport Any classBaseSpecification(ABC): @abstractmethod defis_satisfied_by(self, candidate: Any) -> bool: raise NotImplementedError() def__call__(self, candidate: Any) -> bool: return self.is_satisfied_by(candidate) def__and__(self, other: "BaseSpecification") -> "AndSpecification": return AndSpecification(self, other) def__or__(self, other: "BaseSpecification") -> "OrSpecification": return OrSpecification(self, other) def__neg__(self) -> "NotSpecification": return NotSpecification(self) @dataclass(frozen=True) classAndSpecification(BaseSpecification): first: BaseSpecification second: BaseSpecification defis_satisfied_by(self, candidate: Any) -> bool: return self.first.is_satisfied_by(candidate) and self.second.is_satisfied_by(candidate) @dataclass(frozen=True) classOrSpecification(BaseSpecification): first: BaseSpecification second: BaseSpecification defis_satisfied_by(self, candidate: Any) -> bool: return self.first.is_satisfied_by(candidate) or self.second.is_satisfied_by(candidate) @dataclass(frozen=True) classNotSpecification(BaseSpecification): subject: BaseSpecification defis_satisfied_by(self, candidate: Any) -> bool: return not self.subject.is_satisfied_by(candidate)
C++
[edit ]template<classT> classISpecification { public: virtual~ISpecification()=default; virtualboolIsSatisfiedBy(TCandidate)const=0; virtualISpecification<T>*And(constISpecification<T>&Other)const=0; virtualISpecification<T>*AndNot(constISpecification<T>&Other)const=0; virtualISpecification<T>*Or(constISpecification<T>&Other)const=0; virtualISpecification<T>*OrNot(constISpecification<T>&Other)const=0; virtualISpecification<T>*Not()const=0; }; template<classT> classCompositeSpecification:publicISpecification<T> { public: virtualboolIsSatisfiedBy(TCandidate)constoverride=0; virtualISpecification<T>*And(constISpecification<T>&Other)constoverride; virtualISpecification<T>*AndNot(constISpecification<T>&Other)constoverride; virtualISpecification<T>*Or(constISpecification<T>&Other)constoverride; virtualISpecification<T>*OrNot(constISpecification<T>&Other)constoverride; virtualISpecification<T>*Not()constoverride; }; template<classT> classAndSpecificationfinal:publicCompositeSpecification<T> { public: constISpecification<T>&Left; constISpecification<T>&Right; AndSpecification(constISpecification<T>&InLeft,constISpecification<T>&InRight) :Left(InLeft), Right(InRight){} virtualboolIsSatisfiedBy(TCandidate)constoverride { returnLeft.IsSatisfiedBy(Candidate)&&Right.IsSatisfiedBy(Candidate); } }; template<classT> ISpecification<T>*CompositeSpecification<T>::And(constISpecification<T>&Other)const { returnnewAndSpecification<T>(*this,Other); } template<classT> classAndNotSpecificationfinal:publicCompositeSpecification<T> { public: constISpecification<T>&Left; constISpecification<T>&Right; AndNotSpecification(constISpecification<T>&InLeft,constISpecification<T>&InRight) :Left(InLeft), Right(InRight){} virtualboolIsSatisfiedBy(TCandidate)constoverride { returnLeft.IsSatisfiedBy(Candidate)&&!Right.IsSatisfiedBy(Candidate); } }; template<classT> classOrSpecificationfinal:publicCompositeSpecification<T> { public: constISpecification<T>&Left; constISpecification<T>&Right; OrSpecification(constISpecification<T>&InLeft,constISpecification<T>&InRight) :Left(InLeft), Right(InRight){} virtualboolIsSatisfiedBy(TCandidate)constoverride { returnLeft.IsSatisfiedBy(Candidate)||Right.IsSatisfiedBy(Candidate); } }; template<classT> classOrNotSpecificationfinal:publicCompositeSpecification<T> { public: constISpecification<T>&Left; constISpecification<T>&Right; OrNotSpecification(constISpecification<T>&InLeft,constISpecification<T>&InRight) :Left(InLeft), Right(InRight){} virtualboolIsSatisfiedBy(TCandidate)constoverride { returnLeft.IsSatisfiedBy(Candidate)||!Right.IsSatisfiedBy(Candidate); } }; template<classT> classNotSpecificationfinal:publicCompositeSpecification<T> { public: constISpecification<T>&Other; NotSpecification(constISpecification<T>&InOther) :Other(InOther){} virtualboolIsSatisfiedBy(TCandidate)constoverride { return!Other.IsSatisfiedBy(Candidate); } }; template<classT> ISpecification<T>*CompositeSpecification<T>::AndNot(constISpecification<T>&Other)const { returnnewAndNotSpecification<T>(*this,Other); } template<classT> ISpecification<T>*CompositeSpecification<T>::Or(constISpecification<T>&Other)const { returnnewOrSpecification<T>(*this,Other); } template<classT> ISpecification<T>*CompositeSpecification<T>::OrNot(constISpecification<T>&Other)const { returnnewOrNotSpecification<T>(*this,Other); } template<classT> ISpecification<T>*CompositeSpecification<T>::Not()const { returnnewNotSpecification<T>(*this); }
TypeScript
[edit ]exportinterfaceISpecification{ isSatisfiedBy(candidate:unknown):boolean; and(other:ISpecification):ISpecification; andNot(other:ISpecification):ISpecification; or(other:ISpecification):ISpecification; orNot(other:ISpecification):ISpecification; not():ISpecification; } exportabstractclassCompositeSpecificationimplementsISpecification{ abstractisSatisfiedBy(candidate:unknown):boolean; and(other:ISpecification):ISpecification{ returnnewAndSpecification(this,other); } andNot(other:ISpecification):ISpecification{ returnnewAndNotSpecification(this,other); } or(other:ISpecification):ISpecification{ returnnewOrSpecification(this,other); } orNot(other:ISpecification):ISpecification{ returnnewOrNotSpecification(this,other); } not():ISpecification{ returnnewNotSpecification(this); } } exportclassAndSpecificationextendsCompositeSpecification{ constructor(privateleftCondition:ISpecification,privaterightCondition:ISpecification){ super(); } isSatisfiedBy(candidate:unknown):boolean{ returnthis.leftCondition.isSatisfiedBy(candidate)&&this.rightCondition.isSatisfiedBy(candidate); } } exportclassAndNotSpecificationextendsCompositeSpecification{ constructor(privateleftCondition:ISpecification,privaterightCondition:ISpecification){ super(); } isSatisfiedBy(candidate:unknown):boolean{ returnthis.leftCondition.isSatisfiedBy(candidate)&&this.rightCondition.isSatisfiedBy(candidate)!==true; } } exportclassOrSpecificationextendsCompositeSpecification{ constructor(privateleftCondition:ISpecification,privaterightCondition:ISpecification){ super(); } isSatisfiedBy(candidate:unknown):boolean{ returnthis.leftCondition.isSatisfiedBy(candidate)||this.rightCondition.isSatisfiedBy(candidate); } } exportclassOrNotSpecificationextendsCompositeSpecification{ constructor(privateleftCondition:ISpecification,privaterightCondition:ISpecification){ super(); } isSatisfiedBy(candidate:unknown):boolean{ returnthis.leftCondition.isSatisfiedBy(candidate)||this.rightCondition.isSatisfiedBy(candidate)!==true; } } exportclassNotSpecificationextendsCompositeSpecification{ constructor(privatewrapped:ISpecification){ super(); } isSatisfiedBy(candidate:unknown):boolean{ return!this.wrapped.isSatisfiedBy(candidate); } }
Example of use
[edit ]In the next example, invoices are retrieved and sent to a collection agency if:
- they are overdue,
- notices have been sent, and
- they are not already with the collection agency.
This example is meant to show the result of how the logic is 'chained' together.
This usage example assumes a previously defined OverdueSpecification class that is satisfied when an invoice's due date is 30 days or older, a NoticeSentSpecification class that is satisfied when three notices have been sent to the customer, and an InCollectionSpecification class that is satisfied when an invoice has already been sent to the collection agency. The implementation of these classes isn't important here.
Using these three specifications, we created a new specification called SendToCollection which will be satisfied when an invoice is overdue, when notices have been sent to the customer, and are not already with the collection agency.
varoverdue=newOverdueSpecification(); varnoticeSent=newNoticeSentSpecification(); varinCollection=newInCollectionSpecification(); // Example of specification pattern logic chaining varsendToCollection=overdue.And(noticeSent).And(inCollection.Not()); varinvoices=InvoiceService.GetInvoices(); foreach(varinvoiceininvoices) { if(sendToCollection.IsSatisfiedBy(invoice)) { invoice.SendToCollection(); } }
References
[edit ]- Evans, Eric (2004). Domain Driven Design. Addison-Wesley. p. 224.
External links
[edit ]- Specifications by Eric Evans and Martin Fowler
- The Specification Pattern: A Primer by Matt Berther
- The Specification Pattern: A Four Part Introduction using VB.Net by Richard Dalton
- The Specification Pattern in PHP by Moshe Brevda
- Happyr Doctrine Specification in PHP by Happyr
- The Specification Pattern in Swift by Simon Strandgaard
- The Specification Pattern in TypeScript and JavaScript by Thiago Delgado Pinto
- specification pattern in flash actionscript 3 by Rolf Vreijdenberger