<!--DEBUG:--><!--DEBUG:dc3-united-states-software-in-english-pdf-2--><!--DEBUG:--><!--DEBUG:dc3-united-states-software-in-english-pdf-2--><!--DEBUG-spv-->{"id":1808153,"date":"2021-01-01T04:39:00","date_gmt":"2021-01-01T02:39:00","guid":{"rendered":"http:\/\/nhub.news\/?p=1808153"},"modified":"2021-01-01T06:03:07","modified_gmt":"2021-01-01T04:03:07","slug":"how-to-make-your-reviewer-cry-using-java-optional","status":"publish","type":"post","link":"http:\/\/nhub.news\/ru\/2021\/01\/how-to-make-your-reviewer-cry-using-java-optional\/","title":{"rendered":"How to Make Your Reviewer Cry Using Java Optional"},"content":{"rendered":"<p style=\"text-align: justify;\"><b>This article talks about some of the most common and least addressed pitfalls of Java Optional usage, and how to avoid misusage.<\/b><br \/>\nJoin 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\u2019s 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\u2019t 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\u2019s review some definitions and see what Optional is. As a Java developer, you should have encountered the infamous NullPointerException that occurs when you\u2019re 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\u2019s 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: &#8216;when should we use Optional?&#8217; Optional is primarily intended for use as a method return type where there is a clear need to represent &#8216;no result,&#8217; and where using null is likely to cause errors. A variable whose type is Optional should never itself be null; it should always point to an Optional instance. So we can extract the following points from the JavaDoc descriptions: Keeping in mind these subtle points, you can simply spot most of the Optional related code smells. Now, it\u2019s time to go through the four most common Optional pitfalls. One of the most common mistakes I usually face in code reviews is using an if\/else block to handle the circumstances that theOptionalvariable doesn\u2019t contain a non-null value (as previously mentioned in theOptionaldefinition). Check this out: Suppose that you intend to find a user by a specific cell number from the database. Then you receive anOptionalvariable from the corresponding DAO class. Now, you want to check if there\u2019s a user with the cell number you have provided. What\u2019s wrong with the above code? Doesn\u2019t work? Honestly, it works like a charm. However, it\u2019s not elegant; it\u2019s something like twisting wood screws with a wrench. Now, check the following code snippet: Using theorElseThrow, you can do the same thing more concisely and elegantly without any need togetmethod. You can also use its no-argument version oforElseThrowintroduced in Java 10. The second common pitfall may emerge while usingorElseororElseGet. It seems these methods do the same thing; however, there is a significant difference not that fancy like the previous one. Let\u2019s have a look at their signatures and corresponding Javadoc: Regarding the above signatures, the first difference is crystal clear:orElseaccepts a generic object as an argument; however,orElseGetaccepts a supplier function that produces a value. So what? You are right; it may seem negligible. However, it\u2019s not that easy. Let\u2019s check the following sample: What\u2019s the output of the above code snippet? As you see, the number is anOptionalvariable initiated with the value of 10. So we don\u2019t expectorElseGetto do something. Here\u2019s the output: That\u2019s super easy, right? Now check this one: Everything is the same as the previous example except the second line in which we have usedorElseinstead oforElseGet. We don\u2019t expect theorElseto do something yet because ournumberhas a value. Just stop here and guess the output! Same as the previous one? No! The output is: TheorElseparameter always gets evaluated, even if the Optional variable contains a value. However, the supplier method passed to theorElseGetonly gets evaluated when theOptionalvariable is empty. That\u2019s why the second output is different. Note that this could affect the performance drastically in cases you useorElseand pass it a complex method. The other common mistake I usually encounter in code reviews is somehow philosophical; that\u2019s using orElse(null). What\u2019s wrong with it? To find the answer, let\u2019s review the motivation of Optional existence. As I previously mentioned, Optional exists to help you not to face the problems caused by null references such as NullPointerException. We also talked about the orElse method in the previous section. Now, put these two parts together. Does it make any sense to ask our Optional object to return null if it\u2019s empty and doesn\u2019t contain a value? The orElse method is a proper way to return an alternative value in the cases the Optional object is empty. Returning null, questions the usage of Optional. You may prefer to use a null reference instead of Optional; it\u2019s ok, although I never recommend it. However, mixing these two ideas is somehow misleading. At the first glance, the code seems null safe; however, you may face null reference issues, sooner or later. Before describing the last and weirdest case, let\u2019s see how it happens. Let\u2019s get back to the previous example. Suppose that thefindByCellNumberis something like this: As you see, this method returnsnullin a specific condition. Suppose that the database is down and the author handles the exception and returnsnullin this situation (BAD PRACTICE, don\u2019t try this at home). So, there are some circumstances where you try to get theOptionalvalue, but you encounter aNullPointerException. Look at this: We expect the method to return anOptionalthen we useorElseThrow; however, it returnsnull. So, our try leads to an exception. How to avoid this issue? This is the point: as previously mentioned, an Optional MUST not be null. Keeping in mind these points, you can prevent most of the common pitfalls while using Optional. Published at DZone with permission of Majid Abarghooei. See the original article here. Opinions expressed by DZone contributors are their own.<\/p>\n<script>jQuery(function(){jQuery(\".vc_icon_element-icon\").css(\"top\", \"0px\");});<\/script><script>jQuery(function(){jQuery(\"#td_post_ranks\").css(\"height\", \"10px\");});<\/script><script>jQuery(function(){jQuery(\".td-post-content\").find(\"p\").find(\"img\").hide();});<\/script>","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1808152,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[93],"tags":[],"_links":{"self":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/posts\/1808153"}],"collection":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/comments?post=1808153"}],"version-history":[{"count":1,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/posts\/1808153\/revisions"}],"predecessor-version":[{"id":1808154,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/posts\/1808153\/revisions\/1808154"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/media\/1808152"}],"wp:attachment":[{"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/media?parent=1808153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/categories?post=1808153"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/nhub.news\/ru\/wp-json\/wp\/v2\/tags?post=1808153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}