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:
- The Single Responsibility Principle
- It produces a Side Effect
Hopefully this serves as a good reminder to all of us OO programmers out there.