Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are fluent interfaces a violation of the Command Query Separation Principle?

I started writing a fluent interface and took a look at an older piece Martin Fowler wrote on fluent interfaces (which I didn't realize he and Eric Evans coined the term). In the piece, Martin mentions that setters usually return an instance of the object being configured or worked on, which he says is a violation of CQS.

The common convention in the curly brace world is that modifier methods are void, which I like because it follows the principle of CommandQuerySeparation. This convention does get in the way of a fluent interface, so I'm inclined to suspend the convention for this case.

So if my fluent interface does something like:

myObject
  .useRepository("Stuff")
  .withTransactionSupport()
    .retries(3)
  .logWarnings()
  .logErrors();

Is this truly a violation of CQS?

UPDATE I broke out my sample to show logging warnings and errors as separate behaviors.

like image 798
David Hoerster Avatar asked Mar 16 '12 18:03

David Hoerster


1 Answers

Yes, it is. All those methods are obviously returning something, and equally obviously they have side effects (judging from the fact that you don't do anything with the return value, yet you do bother to call them). Since the definition of CQS states that mutators should not return a value we have a clear-cut violation in our hands.

But does it matter to you that CQS is violated? If the fluent interface makes you more productive all things considered, and if you consider it a well-known pattern with equally well-known benefits and drawbacks, why should it matter that it violates principle X on paper?

like image 95
Jon Avatar answered Nov 02 '22 17:11

Jon