Wednesday, February 10, 2010

Argument management

So you wanted to beef up your JavaScript utility by adding a bunch of config options and now you have a constructor with 10 arguments.

Fortunately JavaScript does not support function overloading, so you only have to supply arguments up to the last non null value. Unfortunately, if you only want to provide arguments 1, 6, 7 and 10 you also need to specify a lot of null arguments in between - and you need to count the null arguments very carefully to be certain exactly which value you are assigning to which argument. And pity anyone who is trying to read your code.

function CleverThing(element, duration, rotation, suspension, gravitation, gradation, hesitation, gestation, scale, color) {
   this.element = element;
   this.duration = duration;
   this.rotation = rotation;
   ... ... 
}

var newThing = new CleverThing('arrow', null, null, null, null, 80, 200, null, null, '#FF0000' );

Object literals to the rescue. Merge all your optional arguments into one, call it something like 'options', and assign attributes only as required



function CleverThing(element, options) {
   this.element = element;
   this.duration = options.duration;
   this.rotation = options.rotation;
   ... ... 
}

var newThing = new CleverThing('arrow',{gradation:80, hesitation:200, color:'#FF0000'});

Now you only need pass what you need and anyone viewing the statement can plainly see the intention. Oh and of course you can now pass the options in any order.

No comments:

Post a Comment