Wednesday, 19 June 2013

Command Query Separation

Command Query Separation


In the past couple of months I have moved back to being a full time developer and as with anything that you do over the years you forget things. If you are anything like me you get excited about the concepts that you rediscover. This is how I felt with the concept of Command Query Separation.

The concept is quite simple and stated very well in wikipedia

It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects.

Or simply in the book that coined the term:

Command-Query Separation principle - Functions should not produce abstract side effects.

Well why is it important. Well if you remember we write code for human beings.

I had a method that did the following:

def find_user
  User.find(@id).tap { |user|
     notify(user)
  }
end

Sure this code seems harmless, however this method violates a few principles:

  1. The Single Responsibility Principle
  2. It produces a Side Effect
Hopefully this serves as a good reminder to all of us OO programmers out there.

No comments:

Post a Comment