Method chaining

 

Method chaining in OOP is usually considered “bad practice” because:

 

+ More effort to debug when error (the line with 3+ possible method)

+ From a designer point of view, it looks like every method will be a “mutator” method, which also returns certain type which may be not suitable when extended (inheritance).

participant.addSchedule(events[1]).addSchedule(events[2]).setStatus('attending').save();

 

However, with more powerful IDE and debugging tools (log, etc), it’s now acceptable to have method chaining, as long as it helps clarity and more intuition for the code (i.e. looks cleaner and easier to see the logic/flow).

Usually it is used along with Builder pattern.

The implementation of OOP languages like Java will typically hold the reference to itself by

   return this;

at the end of the method. For Python/Ruby it will be

return self;

 

OK, now that it is a Thing, people should “coin” some cute name. Fluent Interface. Sometimes we can call that “Fluent Interface” pattern.

(Perhaps I should edit this post to have old date 2003 to be the first “claim-er” of the name).

 

 

In JDK code we can see it in some new API, such as Calendar API. To be specific, check source code of Calendar.Builder (Java 8+).

 

./.

 

 

Advertisements

About DucQuoc.wordpress.com

A coder, husband and brother...
This entry was posted in Coding. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s