{"id":466,"date":"2009-10-08T17:59:14","date_gmt":"2009-10-08T16:59:14","guid":{"rendered":"http:\/\/www.leading-edge-dev.de\/?p=466"},"modified":"2010-07-10T10:28:36","modified_gmt":"2010-07-10T09:28:36","slug":"specification-pattern-obsolete","status":"publish","type":"post","link":"https:\/\/www.minddriven.de\/index.php\/technology\/dot-net\/c-sharp\/specification-pattern-obsolete","title":{"rendered":"Is the Specification Pattern obsolete?"},"content":{"rendered":"<p>I&#8217;m a guy who loves many of the new patterns that I get to know. But sometimes when I show that pattern to colleagues around me, they tilt their heads and say: &#8222;Arrrm, who needs this?&#8220;. Often they help me to get back to the ground and think again about intents and benefits of one or the other pattern.<\/p>\n<p>Currently I&#8217;m rethinking the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Specification_pattern\">Specification Pattern<\/a>, which has been <a href=\"http:\/\/www.martinfowler.com\/apsupp\/spec.pdf\">introduced<\/a> by Eric Evans and Martin Fowler some time ago and got some attention in the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Domain-driven_design\">DDD<\/a> community and beyond. The intent of the Specification Pattern is to separate the logic for (e.g.) filtering an entity from the entity itself. This responsibility is encapsulated in single classes &#8211; the specifications. Those specifications are given for example to a single method <code>Filter()<\/code> on a <em>repository<\/em>, which takes care of filtering the <em>domain model<\/em> by the specifications. Thus, you bypass the need for having several special methods in your repository which take care of the actual filter operation (such as <code>FilterByCustomerName()<\/code>, <code>FilterByCustomerAddress()<\/code> etc.).<\/p>\n<p>An example interface snippet for a repository of persons with a specification filter method could then be:<\/p>\n<pre class=\"brush:csharp\">interface IPersonRepository\r\n{\r\n    IEnumerable&lt;Person&gt; Filter(ISpecification&lt;Person&gt;\u00a0filterTerm);\r\n    \/\/ ...\r\n}<\/pre>\n<p>Summarized, some key benefits of the Specification Pattern are:<\/p>\n<ul>\n<li><em>Loose coupling<\/em> of the filter logic from the objects being filtered,<\/li>\n<li><em>Single responsibility<\/em>: Interface of repository\/data provider isn&#8217;t polluted with lots of filter methods,<\/li>\n<li>Callers can express in a <em>flexible<\/em> way by which criteria entities can be filtered,<\/li>\n<li><em>Composition<\/em> of specifications (e.g. by a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Fluent_interface\">fluent interface<\/a>) yields to flexible filter queries, for example:<br \/>\n[sourcecode language=&#8217;c#&#8216;]var filter = Filter<person>.By<ageabove>(25).And<workingin>(&#8222;Frankfurt&#8220;)[\/sourcecode]<\/workingin><\/ageabove><\/person><\/li>\n<\/ul>\n<p>But now the provocative question that one could come with: <strong>Who needs the Specification Pattern in times of C# 3.0 and Expressions?<\/strong> This might sound disturbing at first, but let me explain&#8230;<br \/>\nC# 3.0 came up with the new concept of Expressions\/Expression trees. This way, code can be treated as a kind of syntax tree in the program. Developers can extend the tree with additional code portions and then compile it into executable code which can be invoked.<\/p>\n<p>Therefore Expressions seem to give us similar benefits for filtering as specifications do. By using Expressions, we are able to define a single <code>Filter()<\/code> method on the repository, which gets an appropriate Expression as argument. Consumers of the repository can call this method with their custom filter Expressions and thus we&#8217;ve got the same benefits: loose coupling of filter logic and objects to be filtered, flexibility for callers to provide custom filter criteria and the possibility to combine several filter criteria (several Expressions).<br \/>\nOne could argue that with specifications we&#8217;ve got better encapsulation of the filter logic into separate classes. But this can be done with Expressions as well (e.g. by separate wrapper classes or dedicated Expression providers), so that isn&#8217;t a good argument&#8230;<\/p>\n<p>The interface of a repository of persons with a filter that uses Expressions might look like this:<\/p>\n<pre class=\"brush:csharp\">interface IPersonRepository\r\n{\r\n    IEnumerable&lt;Person&gt; Filter(Expression&lt;Predicate&lt;Person&gt;&gt; filterTerm);\r\n    \/\/ ...\r\n}<\/pre>\n<p>This leads again to the question: Do we still need the Specification Pattern or is it already embedded with Expressions in the language (C# 3.0) itself?<\/p>\n<h4>Pattern focus<\/h4>\n<p>First I want to mention that the intent of a <em>pattern<\/em> is not (only) to provide a technical solution, but also a conceptual guideline for a problem at hand. Thus Expressions as technical solution don&#8217;t cover the intent of the Specification Pattern. The Specification Pattern can be implemented with the help of Expressions, but that&#8217;s another point. So, directly comparing the Specification Pattern with Expressions is like an apple-pear-comparison.<\/p>\n<h4>Encapsulation focus<\/h4>\n<p>Let&#8217;s come to use cases when I would prefer the use of dedicated specification classes rather than directly using Expressions.<br \/>\nFirst as a team lead you could want to enforce the use of dedicated specification classes in your development team (thus enforce encapsulation of the filter logic). By giving Expressions or Predicates to filter methods directly,\u00a0 developers would be allowed to define filter expressions whereever they want to. You don&#8217;t have the control over this process and please don&#8217;t trust your project guidelines: If developers are allowed to do something wrong, they will do.<\/p>\n<p>With specifications you can force your team members to write specification classes for their requirements, which leads to enforced <em>encapsulation<\/em>. Furthermore you drive <em>reuse<\/em> of existing specification classes. Other developers are encouraged to use existing specifications, especially because of the additional effort for writing new specifications. By combining several specifications, the reusability aspect is pushed even more.<\/p>\n<h4>Domain model focus<\/h4>\n<p>Giving consumers the full flexibility of defining custom filter criteria with specifications can be very handsome in many situations. However, in other scenarios instead of giving full flexibility, you may want to restrict the set of filters for your domain model. If you focus on your domain, you perhaps want a restricted set of specifications, each with a very specific meaning in your domain! Binding such specifications to your domain model makes the purpose of your domain and how it can\/should be used in terms of filtering much clearer.<\/p>\n<p>Technically, in order to restrict access to a particular set of specifications, you could create sealed specification classes <em>inside<\/em> of your domain model services (same layer as repository). Consumers of the repository would be allowed to call the <code>Filter()<\/code> method on the repository with those specifications (and compositions of those), but they would not be able to create new specifications if you don&#8217;t mark the specification interface as public. This way you get two characteristics: Restricted filtering, which fits into your domain and your use cases on the one hand, and encapsulation\/separation of filter logic and entities which should be filtered on the other hand.<\/p>\n<h4>Bottom line<\/h4>\n<p>This article started with an interesting and provocative question: Is the Specification Pattern obsolete? This question came up with a look at Expressions in C# 3.0. Technically you can achieve similar results when using Expressions instead of implementing the Specification classes by hand. But as the last sections have shown, in my opinion the Specification Pattern is <em>not<\/em> obsolete! As <em>pattern<\/em> it&#8217;s adding very specific value to the plain technical solution, when you take encapsulation and domains into account. Then it clearly goes beyond the technical aspect which many developers see at first sight.<\/p>\n<p>Those are my current thoughts on specifications, but of course my opinions are not carved in stone. What do you think? What points I&#8217;ve missed perhaps? I&#8217;m eager for your comments!<\/p>\n<p><a href=\"http:\/\/www.dotnetkicks.com\/kick\/?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d466\"><img decoding=\"async\" src=\"http:\/\/www.dotnetkicks.com\/Services\/Images\/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.leading-edge-dev.de%2f%3fp%3d466\" border=\"0\" alt=\"kick it on DotNetKicks.com\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;m a guy who loves many of the new patterns that I get to know. But sometimes when I show that pattern to colleagues around me, they tilt their heads and say: &#8222;Arrrm, who needs this?&#8220;. Often they help me to get back to the ground and think again about intents and benefits of one &hellip; <a href=\"https:\/\/www.minddriven.de\/index.php\/technology\/dot-net\/c-sharp\/specification-pattern-obsolete\" class=\"more-link\"><span class=\"screen-reader-text\">Is the Specification Pattern obsolete?<\/span> weiterlesen<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11,7,12],"tags":[177,175,176],"class_list":["post-466","post","type-post","status-publish","format-standard","hentry","category-architecture","category-c-sharp","category-design-patterns","tag-expressions","tag-patterns","tag-specification-pattern"],"_links":{"self":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/466","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/comments?post=466"}],"version-history":[{"count":36,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/466\/revisions"}],"predecessor-version":[{"id":936,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/466\/revisions\/936"}],"wp:attachment":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/media?parent=466"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/categories?post=466"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/tags?post=466"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}