To see what I'm talking about, I've created a function, randRange(), that can take the following method signatures:
- randRange( max )
- randRange( min, max )
In the first invocation, the min is assumed to be zero. In the second invocation, there is no need for assumption as both limits are supplied. Using function-level properties, I am going to define the above two functions using completely different functions off of the core randRange() object:
When we run this code, we get the following console output:
As you can see in the above code, I am defining the randRange() function. But then, I am defining the single and double parameter implementations as properties off of the core randRange() object:
randRange.oneParams = function( max )
randRange.twoParams = function( min, max )
Now, the individual method signatures don't have to worry about any kind of arguments-based logic; all the routing logic is factored out and encapsulated within the core randRange() method. This feels like a really clean separation of concerns that leaves the final implementations extremely focused and easy to understand.
In this particular demo, my routing logic depends only on the number of arguments. You could easily augment this, however, to include type checking for methods using the same number of arguments. You could even use the core method to transform several different signatures into one, unified invocation. In any case, I think the factoring-out of argument-specific logic feels really good.
Want to use code from this post? Check out the license.