You are on page 1of 7

1

OPTIONAL
SCHOOL OF JAVA
MARCH 2019
AGENDA
 THE WHY
 WORKING WITH OPTIONAL
2

 WHEN TO NOT USE OPTIONAL


 GOLDEN RULES

2
WHY?

• No real way of specifying that a method might not


return anything
• Make explicit checks for protecting
3
against
NullPointerException
• Entangled code

3
OPTIONAL<T>

PROPERTIES
 Enables designing more-comprehensible APIs so that by just
reading the signature of a method, you can tell whether you can
expect an optional value.
 Two states:
• Absent 4
• Present
 Immutable
 Wrapper
OPTIONAL VS NULL
 When trying to dereference a null will invariably cause a
NullPointerException
 Optional.empty() is a valid, workable object and it can be invoked in
various ways
 Null forces you to check it explicitly while Optional forces you to
actively unwrap it
 Optional is a separate object (16 bytes!)
4
WORKING WITH OPTIONAL

 Empty Optional
 Optional.empty();

 Optional from a non-null value


 Optional.of(object);
 Throws NPE if object is null

 Optional from a nullable value


 Optional.ofNullable(nullableObject);

5
WHEN NOT TO USE OPTIONAL

 in the domain model layer (not Serializable)


 in DTOs (same reason)
6
 in input parameters of methods
 in constructor parameters

6
GOLDEN RULES

1. Never, ever, use null for an Optional variable or return value


2. Never use Optional.get() unless you can prove that the optional
is present
7
3. Use Optional.get() and Optional.isPresent() as the last resort
4. Don’t use Optional for the sake of it
5. Don’t use Optional in fields, parameters or collections

You might also like