by Sohcahtoa82 · 2y ago · 0 comments
It seems to me that something somehow being assigned a null is a bug, but one that would stick out like a sore thumb. At some point, you're returning a Null, right? Any code calling a function that can return a Null should know that being handed a Null is a possibility and handle it, right?
I'd think that eliminating Nulls is a bandaid over the wrong problem. Or is eliminating Nulls really meant to catch any potential NPE's at compile time as a way for force better error checking?
Well right now, the only way to know is to read comments/docs. The problem is that for many older languages, the signature cannot make it clear that null is a possibility (unless you count "anywhere can be null regardless of the function", which isn't helpful).
The goal is to have a real distinction between can be null and wont be null so that things can be made explicit and the compiler can actually highlight places where the handling is missing.
It's a tool to help do exactly what you describe in a less error-prone way.
That's not what is happening here. The issue with the current iteration of Java is that all type declarations implicitly include `null`. So you can do for example:
// some method
public String getSomeValue();
// client code
String someVal = obj.getSomeValue();
At that point, the caller of the getSomeValue() can't depend on someVal being non-null. You say "Any code calling a function that can return a Null should know that being handed a Null is a possibility and handle it, right?" and that's really the problem. ANY method that returns an object type can return null, so, in theory, it would force all callers to do stuff like `if (someVal != null) ...`, which is really annoying if it has to be all over the place.This proposal makes it clear to callers whether a method can return null, or if it is guaranteed by the type system not to return null. That way, it is now possible for a method to state "I guarantee that I will only return a String, never null", and previously that was not possible (directly in the language at least - there were some kludgey workarounds like the Optional generic type). So this means that clients don't need to do tons of unnecessary null checks.
This is definitely not an issue specific to Java. For example, TypeScript is clear that its types do NOT automatically include null, and it makes coding SO much clearer. For a type to include null (or undefined, but that's a whole other JS-specific ball of wax...) you must explicitly write e.g.:
const foo: string | null;Everyone everywhere always being more careful is the bandaid solution, if you lift the extra non-optional sum type into the type system you solve the problem permanently.