
Null References:
In 1965 while designing Algol W, British scientist Tony Hoars introduced the concept of null to programming languages. It started as a simple concept,
“null is a pointer reference that is not pointing to any value”.
But he did not stop there, he wanted to ensure that the usage of pointer references is absolutely safe, so he made the compiler check for null references and throw errors. This is where everything started downhill.
Here is a great talk from The legend himself.
This compiler’s null check error in Algol W was the seed for java’s dreaded java.lang.NullPointerException
class
Java NullPointerException
Since NullPointerException
can occur almost anywhere in a program, Java designers decided to make it a RuntimeException.
So developers do not need to write any code to catch and recover from it.
However, to avoid runtime mishaps, a programmer should always check null inequality, before accessing any “unknown” references.
Car car = getCarFromSomewhere(); if (car != null){ //Check for null
Make make = car.getMake() ;
if(make!=null) { //Check for null
Model model = make.getModel();
return (model != null) //Check for null
? model.getYear()
: null;
}
}
return null;
Java8 Optional
With the introduction of streams, lambdas & method references in Java8, Java designers provided a way to write fluent code pipelines with method chaining as functional programming. But the imperative programming approach of checking null at each step could clutter the well-written pipeline. To avoid that code clutter, Optional was introduced.
Optional is a simple Container Object which may or may not contain a non-null value.
Optional is not a replacement for null, it’s just a tool with 16 bytes overhead, to help us write fluent code API with method chaining. Unfortunately, it was not used as intended by java designers, looking at its widespread misuse, API Notes was added from Java 9 onwards.
Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.
This note was not present in Java 1.8
This was all about history, in the next story, let’s see some usage and misusage of Optional.
Comments