Design Patterns – Method Chaining Idiom for Building Objects

code-qualitycoding-styledesign-patternsmethod-chainingpatterns-and-practices

I frequently use a pattern where I using method chaining to setup an object, similar to a Builder or Prototype pattern, but not creating new objects with each method call, instead modifying the original object.

Example:

new Menu().withItem("Eggs").withItem("Hash Browns").withStyle("Diner");

Just wondering if there is a name for this pattern and whether it is considered an anti-pattern, because although it can read more fluently, it can lead to long method chains.

Best Answer

Fluent Interface

I've always heard of this method being called a 'fluent interface', as coined by Eric Evans (of Domain Driven Design fame) and Martin Fowler (of Agile Manifesto fame).

The main drawbacks are the readability (which some folks love and some hate), and the fact that it can be harder to debug in some cases because the entire chain of actions may be considered a single statement when stepping through it.

I certainly don't consider it an anti-pattern, although I've only used the technique a few times myself.