Best Practices for Designing a Fluent API

imageA fluent API can be incredibly helpful when sharing your application with other developers.

Fluent methods are a hot design idea and they can improve the readability of your code. However, they only make sense in specific scenarios.

A fluent interface (as first coined by Eric Evans and Martin Fowler) is a method for constructing object oriented APIs, where the readability of the source code is close to that of ordinary written prose.

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining [1]). Generally, the context is

  • defined through the return value of a called method
  • self-referential, where the new context is equivalent to the last context
  • terminated through the return of a void context.

— From Fluent Interface


For those designing API, I wanted to recommend a couple articles by Peter Vogel in Visual Studio Magazine:

In the second article, Vogel walks through issues involved in designing the members (methods and properties) that would make up a fluent API.

He says, “The first step in designing a fluent API is to decide which of those activities may be performed together and, as a result, would provide benefits to a developer by allowing the operations to be chained together. …

“In general, in a fluent interface you want to write methods that accept an object, make changes to it and then return the object without making any assumptions about what other operations may or may not be performed on the object.”

Word of advise, “The simplest pattern (just passing the most complete object through the chain) will handle many, but probably not all, of your developers’ scenarios. Without planning, you can find yourself with a non-fluent interface because too many methods break the chains that developers would like to build. Not surprisingly, then, designing a fluent interface is an iterative process that may even lead you back to redesigning the original objects if you want to create as fluent an interface as possible.”