In dynamic language, most language doesn’t provide the function overload mechanism like static language does, which means you cannot define functions with same name but different arguments, and the language itself won’t help you to dispatch the call according to the arguments.
So you have to deal with the overload by yourself in dynamic languages.
In dynamic language, since you have to dispatch the call by yourself, so you can play some tricks during process the arguments. The most common trick is grammar sugar, which can help you simplify the code and increase the readability. And it is a very important feature when you’re building DSL.
Syntax sugar in argument means you can omit something unnecessary or unimportant parameters in specific context, then the function will try to infer and complete the parameters. For example, developer should be able to omit the password parameter if the system enable authentication mechanism. These kind of tricks are very common in dynamic language frameworks, such as jQuery.
Here is a list of some common grammar sugar cases:
- Set default value for omit parameter, such as for jQuery animation function
jQuery.fadeIn([duration] [, callback] )
, you can omit the parameter duration, which is equivalent to provide duration as 400 - Provide different type of value for a same parameter, still the jQuery animation function
jQuery.fadeIn([duration] [, callback] )
, you can provide number for duration, or you can provide string “fast” and “slow” as the value of duration. - Provide a single value rather than a complex hash, such as function jQuery ajax function
jQuery.ajax(settings)
, you can provide a url string, which is equivalent to provide a hash{url: <url string>}
- Pass a single element instead of a array of the element.
After we analyze the cases, we will find that all the grammar sugar is to allow user to provide exactly same information but in different formats. Since all the data are same piece of information, so it should be possible to unify all the information into one format! Which means to support grammar sugar, the major problem is to unify the type of parameter.
Besides unify the type, another important problem is to handle the null values, such asnull
and undefined
in javascript, nil
in ruby, etc.
Here is a piece of ruby code that I parse the argument by unifying the parameter type:
|
|
And here is the test for the code:
|
|
The algorithm in previous code is language independent, so ideally, it could be reused in any language, such as java script or python.