Self Documenting Flexible Parameters

👋 Ciprian on Friday, January 12, 2018 in Blog, JavaScript
Last modified on Monday, January 8, 2018

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Changing the number of JavaScript function parameters can be unproductive because of the need to update other code calling that function whose parameters is changed. Greater chaos could occur if the work is done in teams. Addition or reduction of the number of JavaScript function parameters must be communicated properly to prevent chaos. Updating code to adapt the API changes takes time and decreases productivity.

So what is the solution to this problem? The solution is obviously to never add and reduce the number JavaScript function parameter! Especially those functions decided as public interface.

So instead of doing this to define a public function:

function my_function(param1, param2, param3, param4, param5) {
    // More code here
}

utilize the JavaScript object syntax and jQuery.extend():

function my_function(params) {
    params = $.extend(true, {}, {
        param1: false,
        param2: null,
        param3: '',
        param4: function(a, b) {
            return (a < b);
        },
        param5: null
    }, params);

    // More code here
}

Keep the number of parameter to one, that is the JavaScript object containing attributes replacing function parameters. Although we change the parameters of the function with the object syntax, function interface remains easy to understand, thanks to jQuery.extend(). In fact, we get added value with the ability to provide a default value and data type hint. The attributes whose values are the same with their defaults, don’t need to be passed to the function call. We just need to call the function as in the example below, which param1, param4, and param5 have the same values with their defaults:

my_function({
    param2: "param2 value",
    param3: "param3 value"
});

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

👋 Added by Ciprian on Friday, January 12, 2018 in Blog, JavaScript. Last modified on Monday, January 8, 2018.

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy