DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Understanding Git
  • Creating a Deep vs. Shallow Copy of an Object in Java
  • Java String: A Complete Guide With Examples
  • Java: A Time-Tested Programming Language Still Going Strong

Trending

  • Implementing Stronger RBAC and Multitenancy in Kubernetes Using Istio
  • Auto-Scaling DynamoDB Streams Applications on Kubernetes
  • Chronicle Services: Low Latency Java Microservices Without Pain
  • Performance Optimization Strategies in Highly Scalable Systems
  1. DZone
  2. Coding
  3. Languages
  4. Optional and Objects: Null Pointer Saviours!

Optional and Objects: Null Pointer Saviours!

Abhishek Gupta user avatar by
Abhishek Gupta
CORE ·
Sep. 25, 14 · Interview
Like (0)
Save
Tweet
Share
7.28K Views

Join the DZone community and get the full member experience.

Join For Free

No 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);
}
Slightly better in my personal opinion. There is no risk of an NPE here – in case of a null input, an empty Optional would be returned
public static Optional<String> emptyOptional() {
	return Optional.empty();
}
In case you want to purposefully return an ‘empty’ value. ‘empty’ does not imply null

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 !");
	}
}
A simple way is to check whether or not the Optional wrapper has an actual value (use theisPresent method) – this will make you wonder if its any better than usingif(myObj!=null) ;-) Don’t worry, I’ll explain that as well
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"));
}
One can use the orElse which can be used to return a default value in case the wrapped value is null – the advantage is obvious. We get to avoid the the obvious verbosity of invoking ifPresent before extracting the actual value
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";
		}
	));
}
I was a little confused with this. Why two separate methods for similar goals ? orElse andorElseGet could well have been overloaded (same name, different parameter)

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");
	}
}
What can possibly be null?
  • 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");
	}
}
The requireNonNull method
  • 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;
        }
    }
}
Don’t let NPEs be a pain in the wrong place. We have more than a decent set of tools at our disposal to better handle NPEs or eradicate them altogether !

Cheers! :-)

Object (computer science) Pointer (computer programming)

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Understanding Git
  • Creating a Deep vs. Shallow Copy of an Object in Java
  • Java String: A Complete Guide With Examples
  • Java: A Time-Tested Programming Language Still Going Strong

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: