Method chaining eliminates an extra variable for each intermediate step. The developer is saved from the cognitive burden of naming the variable and keeping the variable in mind.
Method chaining just means chaining multiple method calls into a single expression, rather than using multiple statements. Because the find method returns a different object from the click method. It also encourages people to write code that silently fails.
Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).
I agree that this is subjective. For the most part I avoid method chaining, but recently I also found a case where it was just the right thing - I had a method which accepted something like 10 parameters, and needed more, but for the most time you only had to specify a few. With overrides this became very cumbersome very fast. Instead I opted for the chaining approach:
MyObject.Start()
.SpecifySomeParameter(asdasd)
.SpecifySomeOtherParameter(asdasd)
.Execute();
The method chaining approach was optional, but it made writing code easier (especially with IntelliSense). Mind you that this is one isolated case though, and is not a general practice in my code.
The point is - in 99% cases you can probably do just as well or even better without method chaining. But there is the 1% where this is the best approach.
Just my 2 cents;
Method chaining makes debugging tricky: - You can't put the breakpoint in a concise point so you can pause the program exactly where you want it - If one of these methods throws an exception, and you get a line number, you have no idea which method in the "chain" caused the problem.
I think it's generally good practice to always write very short and concise lines. Every line should just make one method call. Prefer more lines to longer lines.
EDIT: comment mentions that method chaining and line-breaking are separate. That is true. Depending on the debugger though, it may or may not be possible to place a break point in the middle of a statement. Even if you can, using separate lines with intermediate variables gives you a lot more flexibility and a whole bunch of values you can examine in the Watch window that helps the debugging process.
Personally, I prefer chaining methods that only act on the original object, e.g. setting multiple properties or calling utility-type methods.
foo.setHeight(100).setWidth(50).setColor('#ffffff');
foo.moveTo(100,100).highlight();
I do not use it when one or more of the chained methods would return any object other than foo in my example. While syntactically you can chain anything as long as you are using the correct API for that object in the chain, changing objects IMHO makes things less readable and can be really confusing if the APIs for the different objects have any similarities. If you do some really common method call at the end (.toString()
, .print()
, whatever) which object are you ultimately acting upon? Someone casually reading the code might not catch that it would be an implicitly returned object in the chain rather than the original reference.
Chaining different objects can also lead to unexpected null errors. In my examples, assuming that foo is valid, all the method calls are "safe" (e.g., valid for foo). In the OP's example:
participant.getSchedule('monday').saveTo('monnday.file')
...there's no guarantee (as an outside developer looking at the code) that getSchedule will actually return a valid, non-null schedule object. Also, debugging this style of code is often a lot harder since many IDEs will not evaluate the method call at debug time as an object that you can inspect. IMO, anytime you might need an object to inspect for debugging purposes, I prefer to have it in an explicit variable.
Martin Fowler has a good discussion here:
Method Chaining
When to use it
Method Chaining can add a great deal to the readability of an internal DSL and as a result has become almost a synonum for internal DSLs in some minds. Method Chaining is best, however, when it's used in conjunction with other function combinations.
Method Chaining is particularly effective with grammars like parent::= (this | that)*. The use of different methods provides readable way of seeing which argument is coming next. Similarly optional arguments can be easily skipped over with Method Chaining. A list of mandatory clauses, such as parent::= first second doesn't work so well with the basic form, although it can be supported well by using progressive interfaces. Most of the time I'd prefer Nested Function for that case.
The biggest problem for Method Chaining is the finishing problem. While there are workarounds, usually if you run into this you're better off usng a Nested Function. Nested Function is also a better choice if you are getting into a mess with Context Variables.
In my opinion, method chaining is a bit of a novelty. Sure, it looks cool but I don't see any real advantages in it.
How is:
someList.addObject("str1").addObject("str2").addObject("str3")
any better than:
someList.addObject("str1")
someList.addObject("str2")
someList.addObject("str3")
The exception might be when addObject() returns a new object, in which case the unchained code may be a little more cumbersome like:
someList = someList.addObject("str1")
someList = someList.addObject("str2")
someList = someList.addObject("str3")
Edit: My opinions on this have changed over the last 10 years. For mutable objects, I still don't see a lot of benefit, although it is useful for avoiding a little bit of duplication. But now that I favour immutability a lot more, method chaining is my preferred way of doing non-destructive updates, which I use all the 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