Commands vs Queries

There are some fascinating discussions going on over on the mailing list for Avdi Grimm’s excellent e-book, Objects on Rails.

Recently, in a discussion about command-query separation and Dan Kubb posted this little piece of beauty:

One convention I use is that query methods are idempotent and return a
value, while command methods change state, but they can only return
self. This provides a nice fluent interface when working with the
objects, and feels quite natural (to me at least).

Feels natural to me too.

Published by Matt

I write software, and love learning how to do it even better.

Join the Conversation


  1. I’ve started using this convention recently and it’s been great. It makes your API very consistent and has some nice ‘side effects’ like ability to easily chain commands (helpful in some cases).

    That’s a truly great practice I wish more people in Ruby community were using it!

  2. Generally true. is my counter example, perhaps the exception that proves the rule.

Leave a comment

Your email address will not be published. Required fields are marked *