In: Computer Science
Explain the key differences between using if statements to check for null values and using Optional types and why we might prefer that latter.
The if-else statement allows us to select between two alternatives. First, the condition is evaluated. If the result of the evaluation is the value true, the then-statement is executed, otherwise, the else statement is executed. An Optional is essentially a container. It is designed either to store a value or to be "empty" if the value is non-existent - a replacement for the null value. This means that explicit null-checking is no longer needed from a programmer's point of view - it becomes enforced by the language itself.
So the latter one is preferred since it makes your code
more readable and protects it against null pointer
exceptions. So Never Assign Null to an Optional Variable.
Prefer Optional.empty()
to initialize
anOptional
instead of a null
value.
Optional
is just a container/box and it is pointless
to initialize it with null
. When you have
anOptional
and need anull
reference, then
use orElse(null)
. Otherwise, avoid
orElse(null)
. A typical scenario for
usingorElse(null)
occurs when we have
anOptional
and we need to call a method that
acceptsnull
references in certain cases. The purpose of
Optional
is not to replace every single null reference
in your codebase but rather to help design better APIs in
which—just by reading the signature of a method—users can tell
whether to expect an optional value. In addition,
Optional
forces you to actively unwrap an
Optional
to deal with the absence of a value; as a
result, you protect your code against unintended null pointer
exceptions.