Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Marc Aube:
Design Pattern: Specification
May 25, 2015 @ 17:19:47

Marc Aube has a new post to his site that introduces you to the specification design pattern, a technique that's useful for ensuing the current state of an object is valid.

The specification pattern is a software design pattern used to codify business rules that state something about an object. These simple predicates determine if an object's state satisfies a certain business criteria. They can then be combined to form composite specifications using logical operators. Use a specification to encapsulate a business rule which does not belong inside entities or value objects, but is applied to them.

He suggests a few things the pattern could be useful for like validating the current state or define how an object should be created. He gives a few more "real world" examples and then gets into the code to create a custom specification. In his "CustomerIsPremium" spec he defines a single method on an interface to determine if the Customer given is correct. He then creates a class instance and encapsulates the logic inside its "isSatisfiedBy" method. He also includes a bit more complex example, showing how to create a composite specification for handling grouping like "and", "or" and "not" assertions. Finally he looks at how to build specifications that can be passed in and used as selection criteria. He does point out that this can leak database handling into the specification layer, however, and should really be avoided without a inversion of control method in place.

tagged: specification designpattern pattern example composite select validate

Link: http://marcaube.ca/2015/05/specifications/


Trending Topics: