Command Query Separation

Have a look at your current application for a moment and try to split it into two parts – the ‘read-only’ side and the write side. Please notice that I have mentioned the word ‘read-only’ side. As the name suggests, the read-only side is the side of the application that is responsible for reading data from the database and displaying it on the UI. No where during the request is it supposed to save any change back to the database. Displaying data in pagable, sortable grid falls under the ‘read-only’ side of the application. Reports would fall under ‘read-only’ side. These are the requests that do not make any change to the database. In other words, it do not change the state of system

Where-as, the other side of the application i.e the write-side of the application would persist changes made by the users into the database.

Let’s say that you were to architect the read-only and the write sides of the application separately, as though they were two different systems, what would some of the design goals that you would come up with? Try to do this exercise with your current application and put down few design goals in the order of their priorities for each side.

As far as I am concerned, eighty percent of my users are going to use twenty percent of my application. Moreover, this twenty percent of the application consists primarily of the read-only side of the application. Hence, for me, some of the high priority design goals for the read-only side of my applications would be

1. Performance
2. Scalability

By no means am I attempting to suggest that the write-side of the application is any less important. In my case, it is actually the foundation for the read-side and hence is critically important for the success of the system. But, it has different design priorities. Since, it mostly deals with complex business rules and ensures non-corruption of data, some of the design goals that would top the list would be as follows,

1. Data Integrity
2. Maintainability
2. Extendibility
3. Flexibility

Clearly, the architectural needs of the read-only and write sides of my application are different in nature. Is it the same for you also? If it is, then the question we should be asking ourselves is that does it justify applying or rather imposing same architectural patterns to both sides of application just for the sake of symmetry?

Rich object graphs are ideal for write-side of the application. They result in high degree maintainable code. But they start to play nasty in situations where complex joins are needed and high performance is a priority, something that the read-only side of application needs a lot. And really! These old fashioned stored procedures and inline queries works like charm in these kind of situation. But the problem with Stored Procedures and inline query approach is that they do not provide the same kind of maintainability and data integrity that rich object graphs do. Hence, separating out the read-only and the write sides of the application and applying different architectural patterns to both can very well be the answer.

Bertrand Meyer in his book “Object Oriented Software Construction” separates an object’s methods into two categories:

Queries: Return a result and do not change the observable state of the system (are free of side effects). In other words, the read-only methods.

Commands: Change the state of a system but do not return a value. The write methods.

Meyer calls this principle the Command Query Separation. This principle, applied at architectural level leads to a clear segregation of the commands (write operations) and the queries (read-only operation) and lends itself to the flexibility of applying different architectural patterns to the very different design needs of the Command and Query sides of the application.

The S.O.L.I.D code

As they say, “A picture is worth a thousand words”. Just came across some motivational posters on Uncle Bob’s SOLID Principles on software design. If you are a software developer who likes to keep an eye on what’s going on in the object -oriented (OO) development fraternity, chances are that you would have come across the famous clash of OO titans (Joel vs UncleBob). Interesting perspectives, but that’s a different story altogether and will get into that some other time.

Uncle Bob’s SOLID principles are a collection of five OO design principles. These are:

1. Single Responsibility Principle (SRP)
2. Open Closed Principle (OCP)
3. Liskov Substitution Principle (LSP)
4. Interface Segregation Principle (ISP)
5. Dependency Inversion Principle (DIP)

    DIP

THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE.
https://codingcraft.files.wordpress.com/2011/03/dip.jpg

    OCP

SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION BUT CLOSED FOR MODIFICATION.
https://codingcraft.files.wordpress.com/2011/03/ocp.jpg

    LSP

FUNCTIONS THAT USE REFERENCES TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT.
https://codingcraft.files.wordpress.com/2011/03/lsp.jpg

    ISP

CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACES THAT THEY DO NOT USE.
https://codingcraft.files.wordpress.com/2011/03/isp.jpg

    SRP

HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
ABSTRACTION SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTION.
https://codingcraft.files.wordpress.com/2011/03/dip.jpg

Irrespective of whether you are on Uncle Bob’s side or Joel’s side, these principles to me are great pointers to a good software design. Of course, like any other engineering principles, these should not be treated as commandments. Rather the requirements of the project should dictate the degree of relevance of these principles in their case. That is where Coding becomes a Craft and not mere a discipline of science.

With that said, having the mind laden with these principles will definitely put ones thinking in the right direction. In the direction in which the fundamental requirement of all good software design can be achieved – “Loose Coupling”.

Get rid of the “Manager” syndrome.

Are you one of those coders who often find themselves stuck on deciding a meaningful, explanatory name for their newly created classes? Do you frequently end up creating some “Manager” or “Master” class? If so, then beware! There is something wrong going in there with the vision and perception of your classes. Perhaps, you are asking your nice little classes to do too many things for you; they probably are losing their focus and are perplexed about their existance. Perhaps, you burden these poor fellows with too many responsibilities.

Is anything wrong about having a class to do more than one thing? Well, the Single Responsibility Principle (SRP) says “Yes” there is.

Consider the following class:

  GiveMeName
{
public void Save(Employee emp){…}
public List Get(){…}
public double CalculateGross(double basic){…}
public void NotifyEmployee(Employee emp){…}
}
 

This is the what the class does for you:

1. Saves the newly created employee object to the database,

2. gets the list of employees in the database,

3. calculates the Gross from the basic using the business rule,

4. Sends email Notifications to the employees.

Now if you were to give a meaningful, unambiguous and self-explanatory name to the class GiveMeName, what would you name it? Well, confusing … isn’t it?  The confusion is a very good indicator of the fact that we are doing something unfair to the class here. We are making the poor guy cater to too many responsibilities.  I bet the best name you can think (like me) would be Employee or EmployeeManager. This is where we lose the trick.

Try breaking the GiveMeName class into three small classes:

  EmployeeDb
{
public void Save(Employee emp){…}
public List Get(){…}
}
 
  EmployeeGrossCalculator
{
double Calculate(double basic);
}
 
  EmployeeNotifier
{
public void Notify();
}
 

These classes are much more focused and their names are beautifully self-explanatory and suggestive of their purpose and meaning of existence. They tell you why were they born and why do they exist. Thus there would be one and only reason for any of these classes to change, for, there is one and only one responsibility these classes cater. This will ensure Orthogonal code and hence maintainability of your code. It will help your code to stay closer to universal principle of programming – Tight Cohesion and Loose Coupleing.

So next time when you create a class and find that it’s name doesn’t come obviously to you, and you have to satisfy yourself with some “Manager” kind of name with your class, think twice, think if you have taken a leaf out of the book of SRP.