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.
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.
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.