I know there's a 'methodology' where the developer should write such functions, that the return value is always of the same type. So, say we have a function what tends to return an array, and something unwanted happens, like the argument is invalid, in such cases we won't return null
, instead we return an empty array []
. Then the user of the method can be sure, that the returned value will be an array.
I can't remember to the name of the principle, can you help me out please?
Thanks
Example
Instead:
function(arg) {
var res;
if (arg) {
return ['example'];
}
return res;
}
We must set a default value according to the principle:
function(arg) {
var res = [];
if (arg) {
res = ['example'];
}
return res;
}
Note, that in the first case, there's a race condition in the return value (undefined/array), while in the latter case, we return with an array.