30

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.

Garrett Hall
  • 2,192

3 Answers3

43

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.

Eric King
  • 11,008
7

Method chaining like that is usually called a Fluent Interface when there is some kind of flow or discoverability in the chain. Alternatively, you can think of an api like jQuery that relies heavily on method chaining as not 'fluent' because there's not the same emphasis on discoverability -- it's more for convenience.

For your example (using withx, withy) you can consider this a variant of the Builder pattern because you've got a specialized class that, given some state (method calls) knows how to return a properly configured object.

This isn't an anti-pattern if used appropriately.

pfries
  • 451
3

whether it is considered an anti-pattern,

definitely not an anti-pattern. jQuery is probably the most well used implementation of this.

because although it can read more fluently, it can lead to long method chains

Yes it can, but what is the alternative ? You can end up with almost a plain english sentence, with the api guiding you to what is available and appropriate.

NimChimpsky
  • 4,670