Wednesday, January 13, 2010

How Fluent is too Fluent?

Fluent interfaces have become all the rage, and with good reason (although I prefer the adjective fluid to fluent). Their intent is to make code more “readable”. My question is, for whom? An entry level developer who just got finished with their first “Hello World!” app? A senior level developer who started off as a switch flipper on an Altair? My grandmother? While developing my own fluent interfaces, this is a question I have wrestled with. Who is my target audience, and how far do I take it?

Let’s assume that we should gear our fluent API toward any developer who has basic knowledge of the language of our choosing. The next step is to decide how verbose our interface should be.

There are several fluent implementations that I use in my practice and will show as examples of to illustrate the point.

Fluent Validation is a lightweight validation framework. You create a validation rule as follows:

RuleFor(author => author.FirstName)
.WithMessage("First name is a required field.")
.Length(1, 30)
.WithMessage("First name cannot exceed thirty characters.");

Here is a version for a non-existent validation framework that is more verbose, but reads somewhat more like an actual conversation or user story.

.HasA(author => author.FirstName,
"First name is a required field.")
"First name cannot exceed thirty characters.");

Is there any improvement in the level of communication between the first and second example?

Here’s another example. We are all familiar with SQL statements such as:

SELECT ID, Quantity, Price
FROM dbo.Orders

Here is a version that could exist in an O/RM framework:

IWantThe(ID, Quantity, Price)  

Does code that reads like prose communicate more effectively? Does it better convey our intent? Or, is this just a bunch of unnecessary keystrokes?

No comments:

Post a Comment