3

Command-Query Separation "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."

a = [1, 2, 3]
last = a.pop

Here, in Ruby, the pop command returns the item is popped off the Array.

This an example of a command and query within one method, and it seems necessary for it to be so.

If this is the case, is it really a code smell to have a method that is essentially a query as well as a command?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
RyanScottLewis
  • 13,396
  • 16
  • 56
  • 84
  • 2
    Personally, I think that because people expect `pop` on a stack to return the value it takes off the top of the stack, making two methods would just confuse and create chaos. Really, who wants to write `last = a.peek; a.pop` instead of `last = a.pop` just for theoretical "clarity". If you ask me, go with what's actually clearer and makes more sense. Programming clearly isn't an exact science. – Linuxios Apr 09 '13 at 00:34

1 Answers1

4

Stack popping is a well-known exception to CQS. Martin Fowler notes it as a good place to break the rule.

I would say in this case it's not a code smell, but in general it is a code smell.

Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148