Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages and drawbacks of chainable methods?

I really love the philosophy of chaining methods, like jQuery emphasys in its library. I found it quite elegant and clear.

Being primarily Java developper, I've always wondering myself why this practice was not more used in this language. For example, the Collection interface was not designed in the that way (for adding/removing methods), and I found it quite sad.

Is there real cons against this practice or is it just something that has not enough "sex-appeal" before?

like image 438
gizmo Avatar asked Sep 29 '08 12:09

gizmo


People also ask

What is method chaining Why is it bad?

The drawback to self-referential method chaining is that you communicate that multiple method calls are required to do something, and that each call builds off the last. If this is not true, then method chaining could be communicating the wrong thing to other programmers.

Why is method chaining important?

It eliminates the cognitive burden of naming variables at each intermediate step. Fluent Interface, a method of creating object-oriented API relies on method cascading (aka method chaining). This is akin to piping in Unix systems. Method chaining substantially increases the readability of the code.

Can you chain methods?

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.


3 Answers

IMO it is painful to debug as you tend to have no intermediary variables for inspection.

like image 83
leppie Avatar answered Sep 28 '22 12:09

leppie


There's a common problem with chainable methods and inheritance. Assume you have a class C whose methods F1(), F2(), etc. return a C. When you derive class D from C, you want the methods F1, F2, etc to now return a D so that D's chainable methods can be called anywhere in the chain.

like image 27
LBushkin Avatar answered Sep 28 '22 12:09

LBushkin


I really like this approach as well. The only downside I can think of is that it seems a bit awkward at times to 'return this' at the end of every method. For JQuery, for example, it makes it slightly awkward to allow plugins, because you have to say "make sure you don't forget your returns!!" but there's no good way to catch it at compile time.

like image 26
chessguy Avatar answered Sep 28 '22 13:09

chessguy