views:

84

answers:

4

In most modern OO languages chaining methods together is common, and IMHO elegant, practice. In jquery, for example, you often see code like:

$('div').addClass('container').css('color', 'white').length

Does writing your objects to allow this have a name?

+4  A: 

This is called a Fluent Interface.

Resources

Pascal Thivent
ah.. thanks. Now, how did I miss that in the first place :)
thomasmalt
@thomas You're welcome.
Pascal Thivent
+1 for being right and awesome in general :)
willcodejavaforfood
+1  A: 

It's typically called "fluent" where each method returns a reference to the object you want to deal with next, allowing you to chain calls together.

In jQuery tutorials and such you'll hear it called "chaining"...it's just another description more heavily used in the community of what it allows not what it is, it's still a fluent interface.

Nick Craver
I don't think that's *quite* correct, they aren't synonyms - chaining is the mechanism a fluent interface supports, i.e. chaining is in usage, fluent is in design.
annakata
@annakata - I think you're confusing "chaining" as it's used in the community with "method chanining"...the actual term/use by definition. My point was more it's not correctly used in the community. For example in a `$.fn.plugin` style, returning `this` is often referred to in documentation/tutorials as "to enable chaining", not "to keep it fluent". I edited to hopefully make this a bit clearer.
Nick Craver
Don't think I am really, my point is that [method] chaining and fluent interfaces are related but not interchangeable terms, regardless of how "the community" uses them. But that said your edit is a bit clearer now.
annakata
+4  A: 

Method Chaining is the core concept behind building a Fluent Interface

willcodejavaforfood
Method chaining is the core of a fluent interface, so it's not wrong really, but not really the most descriptive term either.
Nick Craver
OK thanks guys :)
willcodejavaforfood
The OP is explicitly asking about the "coding style" that allows method chaining. "Method chaining" doesn't answer the question.
Pascal Thivent
Well, getting useful references to both Method Chaining and Fluid Interface was really helpful to improve my vocabulary and programming nomenclature. So I really wish I could accept both your answers. In the end I accepted @willcodejavaforfood's answer, since it came one minute before @Pascal's :/
thomasmalt
@thomasmalt - thanks :)
willcodejavaforfood
A: 

Douglas Crockford calls it a "cascade-style" of programming.

AutoSponge
and he is, as usual, wrong :P
annakata