Thursday 18 July 2013

Simplifying javascript function parameters

Functions having more than two parameters can easily create confusion and make code difficult to read. Lets look at one such constructor function:


function BuildCar(engine, body, gps, tyres) {
}


To create a new car we call the constructor as:

var car = new BuildCar(new Engine(), new Body(), new Gps(), new Tyres());


In order to build a new car we must provide parameters in correct order. Lets say that we make gps optional, now call to build a car without gps would be:

var car = new BuildCar(new Engine(), new Body(), null, new Tyres());


Although we are able to build car without gps but code is no longer readable.We can improve it by changing BuildCar function to accept an object instead of multiple parameters.

function BuildCar(parts) {
    this.engine = parts.engine;
    this.body = parts.body;
    this.tyres = parts.tyres;
    this.gps = parts.gps || {};
}

var car = new BuildCar({ engine: new Engine(), body: new Body(), tyres: new Tyres() });

By accepting an object as parameter BuildCar can now be easily extended to receive more or less parameters.