Optional and Objects: Null Pointer Saviours!
Join the DZone community and get the full member experience.
Join For FreeNo one loves Null Pointer Exceptions ! Is there a way we can get rid of them ? Maybe . . .
Couple of techniques have been discussed in this post
- Optional type (new in Java 8)
- Objects class (old Java 7 stuff ;-) )
Optional type in Java 8
What is it?
- A new type (class) introduced in Java 8
- Meant to act as a ‘wrapper‘ for an object of a specific type or for scenarios where there is no object (null)
In plain words, its a better substitute for handling nulls (warning: it might not be very obvious at first !)
Basic Usage
It’a a type (a class) – so, how do I create an instance of it?
Just use three static methods in the Optional class
public static Optional<String> stringOptional(String input) { return Optional.of(input); }
Plain and simple – create an Optional wrapper containing the value. Beware – will throw NPE in case the value itself is null !
public static Optional<String> stringNullableOptional(String input) { if (!new Random().nextBoolean()) { input = null; } return Optional.ofNullable(input); }
public static Optional<String> emptyOptional() { return Optional.empty(); }
Alright – what about consuming/using an Optional?
public static void consumingOptional() { Optional<String> wrapped = Optional.of("aString"); if (wrapped.isPresent()) { System.out.println("Got string - " + wrapped.get()); } else { System.out.println("Gotcha !"); } }
public static void consumingNullableOptional() { String input = null; if (new Random().nextBoolean()) { input = "iCanBeNull"; } Optional<String> wrapped = Optional.ofNullable(input); System.out.println(wrapped.orElse("default")); }
public static void consumingEmptyOptional() { String input = null; if (new Random().nextBoolean()) { input = "iCanBeNull"; } Optional<String> wrapped = Optional.ofNullable(input); System.out.println(wrapped.orElseGet( () -> { return "defaultBySupplier"; } )); }
Anyway, the only obvious difference here is the parameter itself – you have the option of providing a Lambda Expression representing instance of a Supplier<T> (a Functional Interface)
How is using Optional better than regular null checks????
- By and large, the major benefit of using Optional is to be able to express your intent clearly – simply returning a null from a method leaves the consumer in a sea of doubt (when the actual NPE occurs) as to whether or not it was intentional and requires further introspection into the javadocs (if any). With Optional, its crystal clear !
- There are ways in which you can completely avoid NPE with Optional – as mentioned in above examples, the use of Optional.ofNullable (during Optional creation) andorElse and orElseGet (during Optional consumption) shield us from NPEs altogether
Another savior! (in case you can’t use Java 8)
Look at this code snippet
package com.abhirockzz.wordpress.npesaviors; import java.util.Map; import java.util.Objects; public class UsingObjects { String getVal(Map<String, String> aMap, String key) { return aMap.containsKey(key) ? aMap.get(key) : null; } public static void main(String[] args) { UsingObjects obj = new UsingObjects(); obj.getVal(null, "dummy"); } }
- The Map object
- The key against which the search is being executed
- The instance on which the method is being called
When a NPE is thrown in this case, we can never be sure as to What is null?
Enter The Objects class
package com.abhirockzz.wordpress.npesaviors; import java.util.Map; import java.util.Objects; public class UsingObjects { String getValSafe(Map<String, String> aMap, String key) { Map<String, String> safeMap = Objects.requireNonNull(aMap, "Map is null"); String safeKey = Objects.requireNonNull(key, "Key is null"); return safeMap.containsKey(safeKey) ? safeMap.get(safeKey) : null; } public static void main(String[] args) { UsingObjects obj = new UsingObjects(); obj.getValSafe(null, "dummy"); } }
- Simply returns the value in case its not null
- Throws a NPE will the specified message in case the value in null
Why is this better than if(myObj!=null)
The stack trace which you would see will clearly have theObjects.requireNonNull method call. This, along with your custom error message will help you catch bugs faster . . much faster IMO !
You can write your user defined checks as well e.g. implementing a simple check which enforces non-emptiness
import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Predicate; public class RandomGist { public static <T> T requireNonEmpty(T object, Predicate<T> predicate, String msgToCaller){ Objects.requireNonNull(object); Objects.requireNonNull(predicate); if (predicate.test(object)){ throw new IllegalArgumentException(msgToCaller); } return object; } public static void main(String[] args) { //Usage 1: an empty string (intentional) String s = ""; System.out.println(requireNonEmpty(Objects.requireNonNull(s), (s1) -> s1.isEmpty() , "My String is Empty!")); //Usage 2: an empty List (intentional) List list = Collections.emptyList(); System.out.println(requireNonEmpty(Objects.requireNonNull(list), (l) -> l.isEmpty(), "List is Empty!").size()); //Usage 3: an empty User (intentional) User user = new User(""); System.out.println(requireNonEmpty(Objects.requireNonNull(user), (u) -> u.getName().isEmpty(), "User is Empty!")); } private static class User { private String name; public User(String name){ this.name = name; } public String getName(){ return name; } } }
Cheers! :-)
Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments