4 ms·
It can be useful when calling a function and you want to say "I don't care about parameter X" when null can be an otherwise valid value for that parameter. I'v
by extrapickles 10y ago
It can be useful when calling a function and you want to say "I don't care about parameter X" when null can be an otherwise valid value for that parameter.
I've also found it useful when a function needs to indicate it failed but is in a situation where exceptions are not useful. This is code where the consumer of the function can throw its own much more useful exception or can try to recover from the function failing (eg: it can try and fix the fault). This helps people avoid using exceptions for flow control of the application and lets exceptions be truly exceptional.
Examples:
//3rd party code could dictate 'bar' be in the spot that it is
function needsUndef(foo, bar, other){
if(bar === undefined) bar = expensive_query();
//rest of code
}
needsUndef(42, cachedResultExpensiveQuery, something);
needsUndef(42, undefined, something);
and:
foo = getFromDisk(foo_path);
if(foo === undefined)
foo = getFromNetwork(last_resort);
is much nicer than:
try{
foo = getFromDisk(foo_path);
}catch(ex){
//Yes, I know you can filter exceptions, but what if someone forgets or sets too wide
//of a net?
foo = getFromNetwork(last_resort);
}
or:
if(path_isValid(foo_path) && canReadFromPath(foo_path))
foo = getFromDisk(foo_path);
else foo = getFromNetwork(last_resort);
- kilotaras 10y agoFor second case most people use options in language that have them.