The best solution I’ve found are languages that offer Nullability to have built-in types which cannot be null. For instance, there is both string
and Null<string>
When defining the parameters for a method, you can explicitly specify the regular version. The compiler will then prevent passing a nullOrString to that method.
This solves the problem. Instead of requiring the method to validate all parameters, it moves the problem to client. I.e. elevating the responsibility to the place which will cause the problem.
This also solves a different problem. That is how to avoid validating all the input parameters in every method.
MethodA(Null<string> a) {
if (a == null) { return; }
MethodB(a);
}MethodB(Null<string> b) {
if (b == null) { return; }
console.log(b);
}MethodA(null);
In order to ensure that your inputs are valid, you need to do the check in two places. In one library/service, you likely will do the null checking only in one place (because it is easier that way), but that will eventually cause problems, when there is MethodC
which actually is okay passing a null
along.
This would solve that problem
MethodA(string a) {
MethodB(a);
}
MethodB(string b) {
console.log(b);
}let a = null;
if (a == null) { return; }
MethodA(a);