KapreSoft
From Coding to Cooking to Coins:
Antonio Lagnada's Blog on Software, Music, Food, and Finance

Java Optional - Why Developers Prefer Optional Values

Post Date: 12 May 2019
 
 

Overview

This article discusses the use of Java Optional to introduce optional values instead of null. We will deep dive into understanding why developers prefer the Optional class to clearly communicate an optional value as opposed to a vague null representation of a variable.

This article will also illustrate the use of the functional interface in java.util.Optional to simply and reduce if-else logic in your code. In Java 8, an java.util.Optional class was introduced to treat such values at the type level to steer developers away from null-based programming. When it comes to null-safety in java, often times we are forced to write defensive code. Null checks in code has been around since the beginning. Others might argue that having a null is not the best way to represent whether a value is present or absent. Some may say that having an Optional class type will make the code a lot easier to read. Often times the source of several problems is the null reference to an object. When null is used to indicate the absence of a value, many can encounter the dangers of null.

String version = application.getFeature().getVersion();
String attrValue = application.getFeature().getAttributes().get("attr1");

The code above looks fairly reasonable. The issue occurs when the a feature is not available and a common practice is to return a null reference to represent an absence of a particular feature. The call to getVersion() will try to return a null reference, which will result in a java.lang.NullPointerException at runtime and stop your code from running.

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class MyApplication {
    
    public Optional<Feature> feature;

    public Optional<Feature> getFeature() {
        return feature;
    }

    public static class Feature {
        
        public String version;
        public Optional<Map<String, String>> attributes = Optional.of(new HashMap<>());

        public String getVersion() {
            return version;
        }

        public Optional<Map<String, String>> getAttributes() {
            return attributes;
        }
        
    }
    
}

The code can now be written as:

Optional<MyApplication> app = loader.loadApplication(MyApplication.class);

String version = app.flatMap(MyApplication::getFeature)
                    .map(Feature::getVersion)
                    .orElse("NO VERSION");

Optional.ofNullable(val:Object)

Creates an Optional instance of the supplied argument where the val could be absent (or not present).

String firstName = null;
System.out.println(Optional.ofNullable(firstName).isPresent());
// Output: false

Optional.of(val:Object)

Creates an Optional instance of the passed argument where the val is expected to be present (non-null value).

Example 1

Feature feature = new Feature();
Optional<Feature> optionalFeature = Optional.of(feature); 
System.out.println(Optional.of(optionalFeature).isPresent());
// Output: true

Example 2

A blank string can represent a present (non-null) value.

String firstName = "";
System.out.println(Optional.of(firstName).isPresent());
// Output: true

Replace if (var == null)

Replacing a null-based control block.

Feature feature = application.getFeature();
if (feature != null) {
    System.out.println(feature.getVersion());
}

The null check can now be replaced with:

Optional<Feature> feature = application.getFeature();
if (feature.isPresent()) {
    System.out.println(feature.get().getVersion());
}

Reduce if-else logic using functional methods

Feature feature = application.getFeature();
String version = null;
if (feature != null) {
    version = feature.getVersion();   
}
System.out.println(version);
String version = application.getFeature().map(Feature::getVersion).orElse("NO VERSION");
System.out.println(version);

Streaming calls

The following call can fail several ways when someone along the call chain a null object is returned.

String featureAttribute = app.getFeature().getAttributes().get("attr1");

An typical null-based code would look like this. You can see below how ugly the code gets and the level of nesting it generates.

String attrValue;
MyApplication app = loader.loadApplication(MyApplication.class);
if (app != null) {
    Feature feature = app.getFeature();
    if (feature != null) {
        Map<String,String> attributes = feature.getAttributes();
        if (attributes != null) {
            attrValue = attributes.get("attr1");
        }
    }   
}

The null-based code block can be replaced with the following streaming call using flatMap:

Optional<MyApplication> app = loader.loadApplication(MyApplication.class);
String attrValue = app.flatMap(MyApplication::getFeature)
                      .flatMap(MyApplication.Feature::getAttributes)
                      .map(m -> m.get("attr1"))
                      .orElse("");

The following code looks a lot cleaner and (big AND) there’s no literal null checks.

Conclusion

The Optional-based programming would be best for you to protect your code against null pointers exceptions. The goal of java.lang.Optional will not replace all null reference in your code but rather help create a better and cleaner code.


Related Articles:

Java • int vs long Post Date: 07 Dec 2023
In Java programming, understanding data types is crucial for efficient and error-free coding. Two fundamental data types often encountered are int and long. This article delves into their differences, use cases, and how they impact Java applications. By comprehending the nuances between these types, developers can make informed decisions, optimizing their code for performance and precision.
Java • Custom Annotations In Action Post Date: 06 Dec 2023
In the dynamic landscape of Java programming, custom annotations have become a pivotal tool, revolutionizing code development and maintenance. As specialized metadata, custom annotations in Java empower developers to infuse additional information into their code, enhancing readability, maintainability, and functionality. They simplify complex tasks like serialization and data validation, and improve communication in collaborative coding environments.
Functional Programming with Java Post Date: 03 Dec 2023
Functional Programming (FP) in Java marks a significant shift towards a more efficient and clean coding paradigm, integrating core principles like immutability, pure functions, and higher-order functions into its traditional object-oriented framework. This article delves into the pivotal role of lambda expressions and the Stream API in enhancing code readability and performance.
Java • Understanding the Command Design Pattern Post Date: 03 Dec 2023
The Command Design Pattern is a foundational concept in software engineering, offering a robust framework for encapsulating a request as an object. This article provides an insightful exploration into its mechanics, advantages, and real-world uses. By understanding this pattern, developers can enhance the flexibility, maintainability, and scalability of their software projects.
Java • Deep Dive into the Visitor Design Pattern Post Date: 02 Dec 2023
This article takes a deep dive into the Visitor Design Pattern, a key concept in software engineering for efficient problem-solving. We’ll define the pattern and its place in design patterns, focusing on its core components: the Visitor and Element interfaces. The discussion extends to real-world applications, demonstrating its versatility across different programming languages.
Java vs. C# Post Date: 29 Nov 2023
In the dynamic and ever-evolving world of software development, Java and C# stand as two titans, each with its own unique strengths, philosophies, and ecosystems. This article delves into an in-depth comparison of Java and C#, exploring their historical context, language features, performance metrics, cross-platform capabilities, and much more.
Java • Mockito vs EasyMock Post Date: 26 Nov 2023
Java, a widely-used programming language, has evolved significantly over the years, especially in the realm of testing. In this digital era, where software development is fast-paced and highly iterative, the importance of efficient and reliable testing frameworks cannot be overstated. Among the various tools and libraries available for Java developers, Mockito and EasyMock stand out as popular choices for unit testing.
Java • Single Responsibility Principle Post Date: 23 Nov 2023
The Single Responsibility Principle (SRP), a fundamental concept within the SOLID principles, is crucial in Java programming. It dictates that each class should have only one reason to change, focusing on a single functionality or concern. This approach is particularly effective in Java, known for its robust object-oriented features, where SRP enhances maintainability, readability, and scalability of applications.
Java • Are Static Classes Things Of The Past? Post Date: 22 Nov 2023
Static classes have been a staple in the programming world for decades. Traditionally, a static class is one where all members and functions are static, meaning they belong to the class itself rather than any specific instance of the class. This makes static classes an efficient tool for grouping related functions and data that do not require object instantiation to be accessed.
Java • Multiple Inheritance Using Interface Post Date: 22 Nov 2023
Amongst the many facets of object-oriented programming, the concept of inheritance is fundamental. Multiple inheritance, a feature where a class can inherit from more than one superclass, can be particularly powerful but also complex. Java, however, does not support multiple inheritance directly in the way languages like C++ do. Instead, it offers a robust alternative through interfaces.
Java • Interfaces Are Replacing Abstract Classes Post Date: 22 Nov 2023
The Java programming language, renowned for its robust structure and versatile capabilities, has witnessed a notable evolution in its fundamental components over the years. Among these, the role and functionality of interfaces and abstract classes have undergone significant changes, particularly with the introduction of new features in Java 8.
Java • Decoupling Arbitrary Objects Through Composition Post Date: 22 Nov 2023
In the dynamic landscape of software development, the concept of object decoupling plays a pivotal role in crafting efficient, maintainable, and scalable applications. At its core, object decoupling refers to the design approach where components of a program are separated in such a manner that they are independent, yet functionally complete. This separation ensures that changes in one part of the system minimally impact other parts, facilitating easier updates, debugging, and enhancement.
Java Primitives & Primitive Wrappers Post Date: 16 Nov 2023
Java, a robust and widely-used programming language, stands out for its efficient handling of data types. Central to its functionality are the Java primitives and their corresponding wrapper classes. This article delves into the essence of Java primitives, their types, and the distinction between primitive and non-primitive data types, including examples to illustrate these concepts.
Java • Primitive int vs Integer Best Practices Post Date: 07 Nov 2023
In Java, one of the foundational decisions developers must make pertains to choosing between primitive types and their corresponding wrapper classes, such as int and Integer. Both have their place in Java applications, and understanding their differences is paramount for writing efficient and effective code.
Java • Harnessing Static and Default Methods in Interfaces Post Date: 06 Nov 2023
The arrival of static and default methods in Java 8 marked a significant shift in interface capabilities, expanding their functionality and versatility in Java’s object-oriented ecosystem. This article explores the nuances of these features and their impacts on Java programming, simplifying complex concepts and illustrating their practical applications in modern software development.
Java Modern Collection Utilities Post Date: 06 Nov 2023
Java’s evolution has always been about simplifying complexity and enhancing efficiency. The collection utilities have undergone significant improvements since JDK 8, transitioning from the Collections utility class to the intuitive List.of(), Map.of(), and Set.of() methods.
Java • Concatenating Streams Post Date: 06 Nov 2023
Merging or combining multiple data sequences into a single stream is a common task in Java programming, especially when working with the robust Stream API introduced in Java 8. Understanding how to effectively concatenate streams can greatly simplify your data processing tasks.
Java • AssertJ vs Hamcrest Assertion Frameworks Post Date: 27 Oct 2023
When working with testing frameworks like JUnit or TestNG, selecting the right assertion framework can significantly enhance the readability of your test code and improve the overall quality of your tests. Two of the most popular Java assertion frameworks are AssertJ and Hamcrest.
Java • Unit Testing Best Practices Post Date: 26 Oct 2023
Unit testing is a fundamental aspect of software development, ensuring that each individual unit of source code is thoroughly examined and validated for correctness. With Java being one of the most widely used programming languages, it is crucial to adhere to the best practices for unit testing in Java to maintain the integrity and performance of the software.
Factory Design Pattern Best Practices Post Date: 23 Oct 2023
The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. By following best practices in the implementation of the Factory Pattern, developers can achieve loose coupling, improved maintainability, and enhanced flexibility in their code.
Logback for Beginners Post Date: 19 Oct 2023
Logback, a Java-based logging framework within the SLF4J (Simple Logging Facade for Java) ecosystem, is the preferred choice in the Java community, serving as an enhanced successor to the popular Log4j project. It not only carries forward the legacy of Log4j but also brings to the table a quicker implementation, more comprehensive configuration options, and enhanced flexibility for archiving old log files.
Java Parallel Streams Post Date: 19 Oct 2023
Java, one of the most versatile and widely-used programming languages, has continuously evolved to adapt to the demands of modern application development. With the advent of parallel streams in Java 8, developers have been endowed with a robust tool to optimize performance and bolster efficiency in their applications.
Java • Modern Looping And Filtering with Stream API Post Date: 19 Oct 2023
Java has constantly evolved since its inception, presenting developers with numerous tools and methods to make coding more efficient and readable. Among these are modern techniques for looping and filtering data.
Java • Converting Strings To List Post Date: 19 Oct 2023
When it comes to working with Java, converting strings into lists is a common and essential operation that can significantly enhance your data processing capabilities. Whether you’re a seasoned programmer or just starting, mastering this technique will prove to be invaluable in your coding endeavors.
Observer Design Pattern Post Date: 18 Oct 2023
In the vast realm of software architecture, design patterns serve as the foundational blueprints that enable the creation of flexible, robust, and efficient systems. Among these, the Observer Design Pattern is a beacon, renowned for its ability to adeptly manage changes and relay updates.
Factory Design Pattern Post Date: 18 Oct 2023
Design patterns act as blueprints or templates for designing software solutions. The Factory Design Pattern is a creational pattern focused on object creation. This pattern, a crucial piece of the design structure, provides a guide for developers to create objects without specifying the exact class of the object that will be created.
Java var Best Practices Post Date: 18 Oct 2023
Java, with each release and update, continually evolves to simplify the developer’s journey while preserving its core tenets of readability and robustness. One of the notable introductions in Java 10 was the var keyword. As with most new features, it sparked debates and questions regarding its efficacy and best practices.
URI vs URL in Java Post Date: 16 Oct 2023
In the realm of Java and web development, the terms URL and URI often emerge in discussions, leaving some in a quagmire of confusion. This article aims to elucidate the disparities between the two, elucidating their syntax, utilization in Java, and the nuances that set them apart.
Java vs JavaScript • Which Is In More Demand? Post Date: 02 Oct 2023
Java and JavaScript, despite their similar names, serve distinct purposes within the realm of software development. As both languages continue to evolve and find niches in the modern tech landscape, it’s crucial to understand their differences and their respective market demands.
Java Cloning Strategies Post Date: 23 Jun 2023
Object copying is a fundamental aspect of Java programming, finding relevance and utility in diverse contexts. Whether it’s creating independent copies of objects, maintaining object state, or avoiding unintended side effects, understanding efficient and reliable cloning strategies is essential.
Java Comprehensive Guide Post Date: 17 May 2023
Java is a versatile programming language that has gained widespread popularity for its platform independence and robustness. In this comprehensive guide, we will delve into the various aspects of Java programming, covering essential concepts, tools, and best practices.
Java vs Kotlin Post Date: 16 May 2023
Java vs Kotlin: A Comprehensive Comparison Java and Kotlin are two popular programming languages that have gained significant traction in the software development industry. In this article, we will compare and contrast these languages, exploring their features, advantages, and use cases.
Java • Converting Strings To Map Post Date: 03 May 2023
This article discusses converting a string of key-value pairs that are delimited by a specific character, known as a delimiter, into a Map in Java.
Maven vs Gradle Post Date: 01 May 2023
Maven and Gradle are two of the most popular build automation tools for Java-based projects. Both tools are designed to simplify the build process, manage dependencies, and facilitate project organization.
Java 19 Virtual Threads Post Date: 04 Apr 2023
In this article, we will provide an overview of virtual threads in Java and their use in concurrent programming. We will define what virtual threads are and how they differ from normal threads. Additionally, we will discuss the benefits of virtual threads over traditional concurrency approaches and provide code examples to illustrate the differences between the two.
Decoupling Domain Objects: Simplifying System Architecture Post Date: 31 Mar 2023
When you design an object-oriented system from top to bottom, sometimes the objects that represent the “domain” (what the system is about) don’t match the objects that represent the “entities” (what the system stores). To solve this problem, you can use a technique called “decoupling” to separate the layers of objects.
Java Final Modifier Post Date: 27 Mar 2023
In Java, the final keyword (also known as a modifier) is used to mark a variable, method, or class as immutable, meaning its value or behavior cannot be modified once it has been initialized.
Java Records Post Date: 14 Mar 2023
A Java record is a new feature introduced in Java 14 that allows developers to create a class that is primarily used to store data. A record is essentially a concise way to define a class that consists mainly of state (fields) and accessors (getters).
Java 17 Features Post Date: 14 Mar 2023
JDK 17, introduces several new features and improvements, including enhanced random number generators, new encoding-specific methods for the String class, and default classes for Java ciphers. It also removes the experimental AOT and JIT compilers, and introduces support for Sealed Classes and Records. These changes provide developers with more flexibility and control, making it easier to write efficient and secure Java applications.
Java • Int to String Conversion Guide Post Date: 11 May 2019
In Java, often times the ability to return a string representing the specified integer is a common task. This article illustrates several mechanisms to convert int to a string in Java. In the opposite scenario, the means to resolve an integer representing the value of the specified String. The returned value is an Integer object that is the equivalent integer value of the argument string.
Java • Double to String Conversion | Beginner's Guide Post Date: 11 May 2019
Converting double to a String value in Java has been a typical task to do for software development. This article discusses the various ways on how to convert a double to a string in Java. While there are advantages in representing a double to its String object representation, the opposite task of converting a String object to a double can also be addressed. This document examines the reasons why conversions of double in Java are beneficial for beginners who are learning to develop in java.
Setting Java Compiler Version in Maven Post Date: 27 Aug 2018
This document demonstrates ways to set the java compiler version in maven via the maven.compiler.target property and the maven-compiler-plugin configuration section.
Getting Started with Maven Build System in Java Projects Post Date: 16 Aug 2018
The following page will illustrate how to get started with the maven build system in your java projects.  Use this guide as a reference when using Maven for the very first time.
Getting Started With Java Post Date: 15 Aug 2018
The following page will illustrate how to get started with the Java Programming Language.  In addition, this document provides an overview of how to install java and the environment variables you will need to set.  A hands-on approach illustrates how to compile and run your first Hello World java code.
Getting Started With Gradle Post Date: 14 Aug 2018
The following page will be an excellent guide with getting started with the gradle build system in your Java™ projects.  Use this guide as a reference when using Gradle as a build system for the very first time.