|Written by Ian Elliot|
|Friday, 23 February 2018|
Page 3 of 3
One common use of function chaining is to create a fluent interface to initialize an object, You can initialize everything using the constructor but this often results in a constructor that is very difficult to use. Providing set functions that can be chained produces a neater and more flexible initialization API.
For example, suppose you have an address object which holds a person's details, then you could define the constructor as:
Following this definition you can write things like:
Once you have seen the basic method you can see that it i possible to extend the idea to including methods to modify values that have already been set. For example you could have an addAge method which increments the age field and so on.
A DSL For Calculation
The first problem we have to solve is that, unlike a non-fluent approach to calculation, our functions cannot return the result of the calculation. In fact, the result has to be stored as the state of the calc object. This is another common pattern in using function chaining - what used to be a result often has to be built into the object's state.
The constructor is:
Notice that all of the functions work with this.value and return this.
The range of operations is quite small - square, sqrt, times, setValue and display. Even so, you can now write calculations that look fairly impressive - for example:
You can see that it does start to look like a program in a special language.
For example, if you make the internal state of the object a collection, you can introduce functions which select and even enumerate on the collection. You can arrange for functions to return different types of object to implement conditionals and so on. You can also pass functions within methods to determine what happens. For example:
could be implemented to apply the sin function to each member of the collection and then perform a reduction on the collection using the sum function i.e. form a total of the values in the collection.
If you want to see more examples of using the fluent style then see jQuery or LINQ both of which take function chaining as key design principles.
or email your comment to: firstname.lastname@example.org
|Last Updated ( Thursday, 13 June 2019 )|