Looking for the name of the next principle

I know there a "methodology" when a developer must write such functions so that the return value is always of the same type. So, let's say we have a function that tends to return an array, and something unwanted happens as an argument, 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 return value will be an array.

I can't remember the name of the principle, can you help me?

thank

Example

Instead

function(arg) {
  var res;
  if (arg) {
    return ['example'];
  }
  return res;
}

      

We must set the default value according to the principle:

function(arg) {
  var res = [];
  if (arg) {
    res = ['example'];
  }
  return res;
}

      

Note that in the former case there is a race condition in the return value (undefined / array), and in the latter case we return with an array.

+3


source to share


2 answers


Basically, the following is done to avoid doing null checks in the calling method. This is done not only for array types, but for all object types to handle null / undefined values.

function(arg) {
  var res = []; // initialization of an object
  if (arg) {
    res = ['example'];
  }
  return res;
}

      

For example,

when you call the above function there is no way for the return value to be null or undefined. This precludes adding



if((var x = function(arg)) != null)

check the calling method.

The closest design pattern you can relate to is the Null Object pattern in java.

http://www.tutorialspoint.com/design_pattern/null_object_pattern.htm

+1


source


Then the user of the method can be sure that the return value will be an array



Sounds like a type of security . Although even in type language, you can return easily null

if you document the return type nullable .

0


source







All Articles