Thursday, June 14, 2007

NotJava Script

Here is something I see from time to time:


function MyObjectConstructor(param1, param2, param3, param4, param5, param6)...

....

var o = new MyObjectConstructor('foo', null, null, null, null, 'bar');


That's just how you would do it in java, too... except you would probably create a couple of versions that didn't have every parameter. But, remember, this is NotJava Script, and there is a better way to do this. So, what's wrong with the above in javascript-land? Well:


  • It's up to the caller to figure out what a default value would be. What happens if someone uses MyObjectConstructor('foo', '', '', '', '', 'bar') or MyObjectConstructor('foo',0,0,0,0,'bar') or MyObjectConstructor('foo',undefined,undefined,undefined,undefined,'bar')?

  • It's fragile - the order of parameters is important. "Ok, I want to set default color, that's the 14th paremeter, I've specified 4, so I need 9 nulls..."

  • Adding new parameters can be cumbersome. Removing parameters from the API will break existing callers

  • Readability is weak. Are all those nulls just defaults, or does null mean something here? What is 'foo'?



Javascript's object literals provides a better way:


function MyObjectConstructor(params){
var param1 = params["param1"] || "param1default";
var param2 = params["param2"] || "param2default";
....
}

....

var myObj = new MyObjectConstructor({param1 : 'myParam1Value", param3 : 'myParam3Value'});


Notice:

  • The caller doesn't have to know what the proper default values are.

  • The order that you specify parameters doesn't matter.

  • If you decide to add or remove a parameter, old calling code will still work

  • Readability is much imporved



Also not the use of the || operator. If you read that as "use of the OR operator" - let me tell you about || in javascript. || is the default operator in javascript, not boolean OR. So, A || B returns A if A is "thruthy" and B otherwise. So, think of var a = b || c as "a equals b defaulting to c if b isn't truthy".

0 comments: