OO Tricks: The Art of Command Query Separation
Arun Sasidharan
4659

I came across a Sonarqube rule that required methods to be marked as static if they don’t operate on instance variables (state changes within the defining class). I find this contract useful. The IDE also italicizes static methods, which is helpful in distinguishing static from instance methods.

For instance, let’s consider the Builder pattern. It changes state but still returns a value (i.e. the builder instance itself). Which is a clear violation of command query separation, but is a pragmatic way to build software.

Sometimes, APIs are designed for readability and usability. CQ separation helps, however it’s essential that developers also understand when to violate the principle.

Show your support

Clapping shows how much you appreciated Ragunath Jawahar’s story.