This is a simple guide for understanding and implementing method chaining in java script.

What is method chaining?

Method chaining is a concept of object-oriented programing in which you can stack multiple methods one after the other. Each method returns an object which can be used to call the next method allowing it to be chained together. It also removes the requirement of additional variables for storing intermediate results.

 

Let’s understand with an example.

In this example we will implement a simple calculator which will contain 4 basic operations namely add, subtract, multiply and divide, and we will use method chaining principle to stack one operation after the other and then generate the result. So, let’s begin

Let’s consider four methods for the four basic operations in the class “Calculator”

Each method accepts a parameter “number” then applies the desired operation on the object’s number property and returns the whole object. This is important because for the method chaining to work you have to return the OBJECT not the VALUE.

Now let’s create a new instance of the class we just created and call those methods and log the result

BOOM! Here is the result
The class is initialized with a value of “12” then by calling the “add()” method with a parameter of 10 it becomes 22 then by calling “subtract()” method with a parameter of “2” it becomes 20 then by calling “multiply()” method with a parameter of 5 it becomes 100 and lastly calling the “divide()” method with a parameter of 4 gives us 25.

Bonus Work:

There are a few more things we could do to make it work even better. Right now, it’s returning the entire object which we may or may not want so let’s create a new method that will just return the resulted value not the object, this method will basically be last method in the chain because it will return a VALUE not an OBJECT, remember we need OBJECT to chain methods.

write a new method “result()” which will just return the resulted value

Let’s also add some error handling to each of the methods to make the recipe perfect. Currently, each method is expecting a number but what if we provide string instead?
Let’s handle this…

In order to get rid of any exception, we added a condition to check the type of the parameter. Now lets call the methods again and see the results…

See the difference now, it’s just showing the value not the object. Lastly let’s check the validation as well by calling the “add()” method with a string value of “10”

Great!!! Everything is fine now!

If you enjoyed this post, We’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter, What’s app or Facebook. Thank you!

Trending Posts