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?
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.
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.
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.
IMO it is painful to debug as you tend to have no intermediary variables for inspection.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With