Are fluent interfaces evil? (As some might suggest)… I don’t think so. In fact, I think they are great.
I plan on doing a few posts around this topic in the coming days/weeks (I’m pretty busy…). I wanted to start by addressing some common arguments I’ve come across.
The first concern I’ve seen is that fluent interfaces somehow break encapsulation. Well…I disagree. If the only thing exposed by an object are methods “that do what you tell it to do”, then it does stuff to its private members - not the caller. Just because an object’s method return’s itself, you still have no access to its private internals.
Again, I disagree. The problem with code that is not readable is that the developer has chosen a poor vocabulary. For example, here’s some code that uses a fluent interface:
Here’s what you would normally see:
bool fail = false;
Which one just reads easier? I think the first. Now imagine complex/lengthy code…
One last argument I see is that fluent interfaces leave the user with too many methods to choose from. How does a user know which order to call methods in? My answer: there are ways to limit what methods are available at any given moment in a method chain. There are two ways I know of to do this.
(1) The fluent class implements various interfaces. When a method expects the next call in the chain to be restricted to a certain set of methods, it will simply return its context (itself) casted to that interface.
Going along with the validator theme:
public IValidationResult Is(string someString)
(2) Have a collection of classes which pass the original context around to each other, with each class/type only exposing relevant methods.
public FluentValidationResult Is(string someString)
I don’t think fluent interfaces are evil. Next time I think I would like to look at what I think are benefits to using fluent interfaces.
Do you agree? Disagree? Have I touched a nerve? Let me know in the comments!
Thanks for reading!
Want to see an example of how to use functional programming to improve your C# code?
I also have an e-mail letter where I’ll give you tips, stories and links to help ambitious and passionate developers become tech leaders. I’ll also give you updates about stuff that I’ve been working on ;)
I’ve been building a tool for indie .NET Core developers needing to get their next groundbreaking app or side-project to market faster - without compromising code quality and elegance. It’s called Coravel!. Check it out and let me know what you think ;)