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 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
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Java 8 Elvis Operator

Java 8 Elvis Operator

So when I heard about a new feature in Java 8 that was supposed to help mitigate bugs, I was excited.

Robert Greathouse user avatar by
Robert Greathouse
·
May. 06, 14 · News
Like (5)
Save
Tweet
Share
76.76K Views

Join the DZone community and get the full member experience.

Join For Free

DISCLAIMER: This post contains a rant. Reader discretion is advised.

Null pointers are the bane of software developers. The nefarious NullPointerException or NoReferenceException is know to all Java or C# developers. At best, they are a minor inconvenience. At worst, they can cost companies a lot of money. So when I heard about a new feature in Java 8 that was supposed to help mitigate these bugs, I was excited.

The feature is called “Optional”. There are a lot of existing examples in other languages of how nulls can be easily handled. Indeed, the documentation even cites some of the examples.

What Alternatives to Null Are There?
Languages such as Groovy have a safe navigation operator represented by “?.” to safely navigate through potential null references. (Note that it is soon to be included in C#, too, and it was proposed for Java SE 7 but didn’t make it into that release.) It works as follows:

String version = computer?.getSoundcard()?.getUSB()?.getVersion();

In this case, the variable version will be assigned to null if computer is null, or getSoundcard() returns null, or getUSB() returns null. You don’t need to write complex nested conditions to check for null.

In addition, Groovy also includes the Elvis operator “?:” (if you look at it sideways, you’ll recognize Elvis’ famous hair), which can be used for simple cases when a default value is needed. In the following, if the expression that uses the safe navigation operator returns null, the default value “UNKNOWN” is returned; otherwise, the available version tag is returned.

String version = computer?.getSoundcard()?.getUSB()?.getVersion() ?: “UNKNOWN”;

[snip]

OK, we diverged a bit and all this sounds fairly abstract. You might now wonder, “so, what about Java SE 8?”

After reading that section, I was momentarily excited. The “?” and “?:” operators in groovy are godsends. But, my enthusiasm was quickly halted. To use this new feature, variables have to be wrapped in Optional objects. For instance:

public Optional<Book> findBook(String isbn) {
   Book b = //look up book in some repository that may return "null" for not found
   return Optional.ofNullable(b);
}

So what does the equivalent Elvis operator “?:” look like in Java 8?

String name = computer.flatMap(Computer::getSoundcard)
                          .flatMap(Soundcard::getUSB)
                          .map(USB::getVersion)
                          .orElse("UNKNOWN");

What happened here? How can you tease me with the easy to use syntax and then throw this up? What the heck is flatMap and map? All I’m trying to do is get the version of the usb connected to the soundcard on my computer.

I can see where there are other use cases for Optional as I read through the rest of the documentation page. But I have to wonder if those other features could have somehow been tacked onto the language in a different manner. I fully admit that I am not a language creator, nor have any experience in it. But in APIs that I write, I try to hide away the ugly and leave a nice, easy-to-use front end. The above does not appear to hide the ugly.

To be fair, I have not had any practical experience with the new features in Java 8. So it is possible I do not fully understand how this particular feature will fit in with the new additions. I will keep an open mind and attempt to use the Optional feature when it makes sense. I tend to write mostly in groovy thesedays, so I will happily keep using the “?” an “?:” operators.

Thanks for reading my rant.

Operator (extension) Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • REST vs. Messaging for Microservices
  • Solving the Kubernetes Security Puzzle
  • Full Lifecycle API Management Is Dead
  • Custom Validators in Quarkus

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

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: