|
|
|
|
|
by lukedegruchy
3895 days ago
|
|
Optional (either JDK or Guava) is not perfect but is infinitely better than hand-checking for null. Among other things, it expresses the intent of the API writer that their method may or may not return an absent value and this is expressed via the type system. This is in stark contrast to using null as a primitive, which has no such transparency. For instance, there is no difference in Java's type system between a method that intends to always return a non-null String, and one that intends to return a null String under certain circumstances. Thus it is impossible for the user of the API to determine when to build conditional logic to check for null or when not to bother. In any case, the concept of null as a primitive is fundamentally broken. Due to Java's backward compatibility requirements, it's too late to resolve this in that language. However, newer languages don't need to make this mistake. However, there are "interoperability" requirements for new languages interfaces with legacy runtimes that tempt language designers to build escape hatches. These escape hatches exist in Swift, Kotlin, Rust, etc even though they're not recommended and their usage presents edge cases. Ceylon and Haskell seem to be the only two languages to get this completely right. Ceylon expresses optionality as the union between the present value type and null, which is an actual type separate from Object. An optional String is therefore a String|Null, or a String? Haskell accomplishes this with the Maybe type. All this to say that null should not be a primitive but should be banished to its own corner of the type system with clear compile-time semantics for dealing with the absence of values. |
|