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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java String: A Complete Guide With Examples
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Import a Function/Module in Dataweave
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java

Trending

  • Rebuilding Elasticsearch Under Load: Unsafe Watermarks and a Sampling Blind Spot
  • Part 3: End-to-End Tracing and Observability Across Goose, agentgateway, and Quarkus
  • How You Clear Your HTML5 Canvas Matters
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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.

By 
Robert Greathouse
·
May. 06, 14 · News
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
78.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Related

  • Java String: A Complete Guide With Examples
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Import a Function/Module in Dataweave
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook