Should I create functions/methods for packages/libraries that allow optional parameters to accept null?
In this example below, I set the 3rd and 4th parameter as null
which will act as the default value.
myLibrary.myFunction(1, 7, null, null, true);
Or is this not a good way to go about creating functions for a package and therefore should not accept null
as a parameter value.
myLibrary.myFunction(1, 7, false, 4, true);
My recommendation for APIs that have optional parameters is to have an optional last
options
parameter, every property of which can be left unset. Makes it far clearer to the caller what those properties do.Having to pass in null values seems a bit weird. You can define functions and optional parameters like this:
function myFunction(a = 1, b = 1, c = null, d = null, e = true) { return a * b; }
Then people don’t have to call your function with
myLibrary.myFunction(1, 7, null, null, true);
they just call your library with
myLibrary.myFunction(1, 7);
You could add a default inside the method signature, like:
function myFunction(a = 1, b = 1, c = null, d = null, e = true) { if (c === null) { c = 5; } return a * b * c; }
because if you define it in the method:
function myFunction(a = 1, b = 1, c = 5, d = null, e = true) { return a * b * c; }
then if people still call it with
console.log(myFunction(5, 2, null));
Then the default
c = 5
is overwritten by null, and results in 0.I don’t know if you really need to handle all that though, instead of just doing
c = 5
- if people intentionally call your library with null, and things go wrong…? well yea ok, don’t do that then.But it depends on the use-case. If this is some method deep within a library, and some other calling method might be unintentionally dumping null into it, you could default it inside the method, and handle it