Image for post
Image for post

A few weeks ago, I ran into an interesting piece of code. I did not understand it but I was mind blown. I have been coding for years and this ‘simple’ piece of code left me puzzled. Let’s look at this piece of code.

Creating a User via Method Chaining

Great. It’s super easy to create a user instance using this method. But how does this work? It’s simple.

Basically, the methods return this. Since each method returns this, each method can then be chained to call another method. Each time a method is called the return value is the class itself, thus the after calling the method dot notation can be applied to it effectively chaining it to another method.

Look at the code below.

Helper class, truncated for conciseness

If the code looks a bit strange it’s because I am using the builder design pattern. I have explained this here. I hope you now fully understand how method chaining works. Whether you are using this to execute encapsulation techniques or reduce constructor clutter this is a cool trick to know. Please leave a clap or multiple claps if you found this useful.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store