Sunday, April 22, 2012

Specifications in Javascript

I have learned to love the concept of specifications, derived from the Specification Pattern. While the way that I have used them is really just a subset of the actual pattern – I have found it very easy to introduce into my existing code.

Basically, we want to separate boolean based logic from the domain object so that it can be used by others, and changed independently.  For example given a Person object,


We may have business rules about their name like hasName and isAge.


these examples show how we can easily reuse the logic behind hasName and isAge. Here is what the functions actually look like.


It is worth noting that hasName doesn’t actually have to return a function – because the specification itself doesn’t have any arguments (isAge does). For consistency, I decided that all specifications should wrap a function. The actual specification takes the arguments, and the inner function takes the object to be tested.

This actually only gets us to the point that we can do things like this


not things like


if we have gone through all the effort to create the specification, we might as well make it available right on the domain object. In a dynamic language like javascript that is relatively easy and highly reusable.



I am debating moving specifications into the prototype stack. They aren’t very usable in the typical context of prototype (inheritance), but it would eliminate the need for passing specifications to SpecificationInjector because it would just look for it on the object that was passed to it.

No comments:

Post a Comment