Home > Design Patterns, dotnet 4 > Layer Supertype Pattern

Layer Supertype Pattern

In this post i am going to show another of my favorite pattern called the Layer Supertype Pattern. It’s again a very simple but very useful pattern and was described by Martin Fowler in his famous book Patterns of Enterprise Application Architecture. If you haven’t read this book I strongly recommend you to read this as it will help you in building better Enterprise Applications.

Anyway this is what the definition in the book is :-

It’s not uncommon for all the objects in a layer to have methods you don’t want to have duplicated throughout the system. You can move all of this behavior into a common Layer Supertype.

 

In the past I have implemented various different implementation of this pattern but the common design pattern is that for a layer or suite of component with specialized behaviour we can abstract some behaviour or attribute to a base class so that we can remove some of the duplications.

For example say we are designing a business layer and we have set of business objects the purpose of this layer is to validate domain objects before it can be persisted in a data store. As we can see these business object will encapsulate this functionality from other layers, and its main functionality will be indicate whether the business object itself is valid or not and what the different violation it has from a business rules.

Well that’s a good starting point and things we have identified using our Object Oriented Analysis and Design ( OOAD ) are :-

  • Business Rule (holds the rule definition)
  • A base entity (to state whether the object is valid and what are the violations
  • Business Object ( will implement the Entity Base )

Lets start writing some code :-

BusinessRule.cs

public class BusinessRule
{
   public string Property { get; set; }

   public string Rule { get; set; }

   public BusinessRule(string property, string rule)
   {
      Property = property;
      Rule = rule;
   }
}

EntityBase.cs

public abstract class EntityBase<T>
{
   private readonly List<BusinessRule> _brokenRules = new List<BusinessRule>();
   protected abstract void Validate();

   public IEnumerable<BusinessRule> GetBrokenRules()
   {
      _brokenRules.Clear();
      Validate();
      return _brokenRules;
   }

   protected void AddBrokenRule(BusinessRule businessRule)
   {
      _brokenRules.Add(businessRule);
   }
}

Lets implement a customer class which inherits from the EntityBase class.

Customer.cs

public class Customer : EntityBase<Int32>
{
   public Int32 Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime DOB { get; set; }

   protected override void Validate()
   {
      if (string.IsNullOrEmpty(FirstName))
      {
         AddBrokenRule(new BusinessRule("FirstName","First name cannot be empty"));
      }

      if (string.IsNullOrEmpty(LastName))
      {
         AddBrokenRule(new BusinessRule("LastName", "Last name cannot be empty"));
      }

   }
}

And to complete the task lets write a unit test to check whether we get the desired result or not.

UnitTest.cs

[TestClass]
public class When_using_customer
{
   [TestMethod]
   public void Should_ab_able_to_validate_customer()
   {
      //Arrange
      var customer = new Customer();

      //Act
      var brokenRules = customer.GetBrokenRules().ToList();

      //Assert
      Assert.IsTrue(brokenRules.Count > 0);
   }
}

And now when we run our unit test we get the two broken rules for customer,also if you look at the EntityBase class closely we are using Template method pattern in the GetBrokenRules method which I blogged last year and can be found here.

Advertisements
  1. Nathan
    December 18, 2011 at 2:26 am

    Greetings old friend!

    I like the concept of a separate business rule class. However, I don’t like mixing business rules within the confines of a domain entity for the reason that they usually constitute inter-domain logic or contradistinctions between entities – which results in a violation of the SRP. In my opinion, validation logic can be subsumed by a domain entity as long as it represents a single entity’s internal consistency. Nevertheless, while the validation logic might exist within an entity, it is often good to use an external validator to perform the actual validation check. This appears to be the approach the Patterns and Practices team took in creating EntLib’s VAB.

    Nice post!

    Cheers,

    Nathan

  2. Nathan
    December 19, 2011 at 4:50 am

    Hey Prashant,

    It looks like your blog stripped my last comment… I guess it didn’t like my idea. 😦

    • December 19, 2011 at 8:03 pm

      Hi Nathan,
      It’s good to hear from you and no the blog didn’t stripped your comments, it need human intervention to approve the comment :). Regarding your single responsibility and domain objects if you are doing pure DDD then the validation would be inside the domain object otherwise it will become Anemic Domain Model, also have a look at the concepts of aggregate roots and new architecture frameworks like CQRS framework 🙂

      The idea in the post is about Layer Supertype Pattern and not about validation logic of domain objects. Anyway how are things at your end, hope everything is settled by now.

  3. Nathan
    December 19, 2011 at 11:38 pm

    Hi Prashant,

    All good points, amigo.

    I have been thinking a lot about how to improve the design of enterprise software within the practical constraints of a small team, and where the skills of individual members vary. However, unless everyone on one’s team is an Eric Evans, Mark Seemann or Udi Dahan, pure DDD and CQRS based service boundary implementations are going to be a hard sell. Generally speaking, I think Microsoft (and by extension, the software industry as a whole) has failed to get new developers to think about “how” to build applications instead of just continually improving their options of “what” to build. It seems to me that software design is often an after-thought, whereas it should be the preliminary focus of every project. Yet, DDD is too much for teams unfamiliar with it to expect an improvement in managing complexity (not without a seasoned architect who is involved with the full project lifecycle). Developers need to first learn how and why they should build to abstractions, even if they are not doing (or never will do) TDD. At some level there will always be compromise – that is the nature of the beast. And so wherever necessary, software should be about making such compromises that speak about functional design in the same breath as functional requirements. Anything less won’t be able to also speak about quality.

    Yes, things have settled down a lot now. Thanks for your concern. We did end up moving inter-state, but it still took a year for our little one to improve.

    I hope you and your wife are doing well too.

    Take care,

    Nathan

  4. November 15, 2013 at 6:57 pm

    Nice blog here! Also your web site loads up fast!
    What host are you using? Can I get your affiliate link to your host?

    I wish my web site loaded up as fast as yours
    lol

  5. Tim Rumsey
    May 25, 2014 at 6:25 am

    I am really impressed ѡith үouг writing skills aѕ well аs ԝith the layout оn your
    weblog. Is this a paid theme or ԁid you customize it үourself?

    Anyway keep up the excellent quality writing, іt’s rare tοo seе а great blog like this one today.

  6. Frederick
    May 31, 2014 at 2:39 am

    I really like it whenever people come together and share views.
    Great blog, stick with it!

  7. Jonnagiuin
    November 6, 2014 at 4:23 am

    Great blog here! Also your website loads up fast!
    What host are you using? Can I get your affiliate link to your host?

    I wish my site loaded up as quickly as yours lol

    • November 7, 2014 at 6:51 am

      Thanks Jonnagiuin it’s comments like this makes me blog more and I hope to continue writing good post.

  1. March 7, 2012 at 6:41 pm
  2. September 10, 2012 at 5:08 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: