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);
Having to pass in null values seems a bit weird. You can define functions and optional parameters like this:
Then people don’t have to call your function with
they just call your library with
You could add a default inside the method signature, like:
because if you define it in the method:
then if people still call it with
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