Consider the following code:
function foo(handlers) {
callSomeFunction(handlers.onSuccess, handlers.onFailure);
}
The caller may do:
foo({onSuccess: doSomething, onFailure: doSomethingElse });
or simply just
foo()
if s/he has nothing special to do.
The issue with the above code is that if 'handlers' are undefined, like in the simple foo() call above, then a run-time exception will be thrown during the execution of callSomeFunction(handlers.onSuccess, handlers.onFailure).
For handling such situations one may re-write the foo function as:
function foo(handlers) {
var _handlers = handlers || {};
callSomeFunction(_handlers.onSuccess, _handlers.onFailure);
}
or more structured
function safe(o) {
return o === Object(o) ? o : {};
}
function foo(handlers) {
callSomeFunction(safe(handlers).onSuccess, safe(handlers).onFailure);
}
I tried to find something like the safe() function in libraries such as sugarjs and underscore, but found nothing. Did I miss something? Is there any other utility library that has a similar function?
Just trying not to reinvent the wheel... ;)
BR, Adrian.
P.S. I didn't test the code above, so it may have errors.