Start United States USA — software How to Make Your Reviewer Cry Using Java Optional

How to Make Your Reviewer Cry Using Java Optional

340
0
TEILEN

This article talks about some of the most common and least addressed pitfalls of Java Optional usage, and how to avoid misusage.
Join the DZone community and get the full member experience. I think code review is one of the best sources of inspiration. I see it as an opportunity to learn new things from other software developers sending pull/merge requests. Moreover, sometimes you may need to study a specific subject with more details regarding the under review code. Usually, this process leads to a more profound knowledge of that domain. However, there’s still another fact about code review: after a while, you face some common mistakes. Recently, I reviewed a feature in which I saw an Optional pitfall. Honestly, I had seen that issue several times in different merge requests sent by several developers (from beginners to experienced ones). I know that there are tonnes of articles regarding Java Optional, some of which are quite useful like this one (although I have arguments against some of the cases mentioned in the article) by Anghel Leonard, the author of Java Coding Problems. I don’t want to repeat all of the contents you can simply find by googling. I intend to talk about some of the most common and least addressed pitfalls regarding Optional usage. Before diving into the main subject, let’s review some definitions and see what Optional is. As a Java developer, you should have encountered the infamous NullPointerException that occurs when you’re going to access a null reference. With a quick search, you can find thousands of memes and jokes about null references in Java (and other languages as well). Optional came in to play in Java 8 to help programmers get rid of all of the problems caused by null references. Have a look at this article, from Oracle technical resources, to read more about the motivation of Optional existence in Java. Now we are going to have a look at Optional’s JavaDoc and check the provided definition. A container object which may or may not contain a non-null value. Following this introduction, as an API note, there is an answer to the first question that may come to mind: ‚when should we use Optional?‘ Optional is primarily intended for use as a method return type where there is a clear need to represent ’no result,‘ and where using null is likely to cause errors.

Continue reading...