Service Architecture: DRY vs SRP Principles

When building n-tiered services, the Single Responsibility Principle (SRP) appears to violate the Don’t-Repeat-Yourself (DRY) Principle. This can best be seen when comparing an OData/Entity-Framework service and a more traditional service.

Traditional Service

In a traditional service, to expose a Person entity, at the service layer a Person DTO entity is created which will expose the desired Person entity properties to consumers.

In many cases this leads to code duplication as seen below. This appears to violate the DRY principle!


    public class Person
    {
        public int Age { get; set; }
    }

    public class PersonDTO
    {
        public int Age { get; set; }
    }

OData and Entity Framework

Enter OData and the Entity framework. No longer are DTO objects which duplicate entity properties required. Entity objects are directly exposed to consumers!

Unfortunately, now the Person entity has two reasons two change:

  1. A change in requirements of consumers.
  2. A changing in design from SQL.

This violates the Single Responsibility principle. The person entity now has two reasons to change. So how do we satisfy the DRY and SRP principles? A closer look at the traditional service is required. Below is an expanded set of Domain and Service classes.

    public class Person
    {
        public int Age { get; set; }
        public string CreditCardNumber { get; set; }
    }

    public class PersonDTO
    {
        public int Age { get; set; }
    }

    public class Animal
    {
        public int Age { get; set; }
    }

Now the Person entity contains private information which we don’t want to expose outside of the service layer. No longer is the PersonDTO duplicating all the functionality of the Person entity. Similarly, an additional entity, the Animal class, has been added to show that although there are duplicate properties between the classes, the code is duplicated to serve different purposes. Each class represents a different function of the system. Modelling the Animal and PersonDTO classes as a single class would be poor design. Conversely, having a Person and PersonDTO does not violate the DRY principle.

Advertisements
This entry was posted in Architecture and tagged , , , . Bookmark the permalink.

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