<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raluca Diaconescu on Medium]]></title>
        <description><![CDATA[Stories by Raluca Diaconescu on Medium]]></description>
        <link>https://medium.com/@raluca.diaconescu?source=rss-348bf6f79fb7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kRYfXTfNbSIIwSk_1o-5qQ.jpeg</url>
            <title>Stories by Raluca Diaconescu on Medium</title>
            <link>https://medium.com/@raluca.diaconescu?source=rss-348bf6f79fb7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:44:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raluca.diaconescu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java 8 Optional — A practical use case]]></title>
            <link>https://medium.com/metrosystemsro/java-8-optional-a-practical-use-case-59a8be471607?source=rss-348bf6f79fb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/59a8be471607</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Raluca Diaconescu]]></dc:creator>
            <pubDate>Mon, 24 Jul 2017 10:50:45 GMT</pubDate>
            <atom:updated>2017-07-25T08:29:04.778Z</atom:updated>
            <content:encoded><![CDATA[<p>How many times in your developer life have you encountered a NullPointerException? I would bet your answer to this question is “too many to count”.</p><p>In Java, null values are a convenient way to model “the absence of a value”. But it was also called “a billion-dollar mistake” by its own inventor, Tony Hore, when making an estimation of the cost incurred by fixing the null reference errors. Although intended to “to ensure that all use of references could be absolutely safe, with checking performed automatically by the compiler”, it instead lets us examine an object’s properties only to find out at run time that we are not examining an actual object but a null pointer that will throw the famous NullPointerException. Trying to handle this in code increases and complicates the code (as we will see next).</p><p>Moreover, from a theoretical point of view, it creates a hole in an object oriented system: null values can be assigned to any type reference, so when it is propagated from one part of the application to another, it gives you no hint on what it was initially.</p><p>Let’s assume in a bank we have the following data model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*oDFKC6Kp8OXSpK4Z0YLUSQ.png" /></figure><p>What can happen if we execute the following code for a customer who only has a credit card?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*x5rxXVpigox5ynyb870Y2Q.png" /></figure><p>As you probably guessed, our friend java.lang.NullPointerException will be thrown. The same would happen if the person would no longer have an account.</p><p>A quick solution would be to insert if statements in this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*0nJmGJcFvBiX5JJipqgpyA.png" /></figure><p>This code inserts multiple if blocks, attempting to catch all possible null values but this is an error-prone strategy.</p><p>Trying to fix this type of problems, Java8 creators inspired themselves from functional languages and introduced a new class (java.util.Optional&lt;T&gt;) for modeling an optional value.</p><p>In the above example, if we know a BankCustomer might or might not have an account, then this account should be modeled as an Optional&lt;Account&gt;. When an account is present, the Optional class is just a wrapper over it. If it missing, the Optional class exists, but it contains nothing. From a business point of view, using the Optional signals the developers that a missing value is allowed here.</p><p>The reworked classes would look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*MCSeomqAuYKVs--ZL_FEwQ.png" /></figure><p>In the code above you can see the Optional objects are initiated using the <strong>Optional.empty()</strong> function which returns an empty Optional instance on which we can work without the NullPointerException problem. Actual account/card objects are added using the <strong>Optional.of()</strong> method which returns an Optional with the specified present non-null value. If a null object is given to the <strong>Optional.of(),</strong> a NullPointerException is immediately raised, at the moment of the initialization. This helps track the incorrect behavior at the source instead of waiting for the code to actually access a null value.</p><p>There is also the method <strong>Optional.ofNullable()</strong> which allows us to put a null object in an Optional and not raise an error at the initialization time. But if we call the <strong>get()</strong> method on such a value, we will still have an error, so this only reproduce the null usage problem which we are trying to solve.</p><p>The card id and amount are kept as normal objects, because they are mandatory from a business point of view (a card without an id or an amount has no meaning) and a missing value means the data is wrong and something should be done about it.</p><p>It is important to understand that <strong>Optional class is not a universal solution</strong> to all null values, but <strong>it aims at helping the developer create more self-explained code</strong> that communicates quickly which values are mandatory and which are not.</p><p>Out checking function can now be rewritten as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Xtz-5druyQ4eQKFjXSoUHw.png" /></figure><p>We are using here the <strong>flatMap </strong>and <strong>map </strong>constructs available on streams in Java 8. Because Optional is also a collection with one or no element, we can use the stream methods on it.</p><p>The <strong>map </strong>function lets you convert an object to something else using a transformation function. The result is an Optional object around the expected result type.</p><p>In our case, we transform an Optional&lt;Account&gt; to an Optional&lt;Optional&lt;Card&gt;&gt; and then the Optional&lt;Card&gt; to an &lt;Optional&lt;Double&gt;&gt; using each object’s getter functions.</p><p>The <strong>flatMap </strong>function does the same as <strong>map </strong>but also flattens multiple layers of Optional into only one: from Optional&lt;Optional&lt;Card&gt;&gt; to &lt;Optional&lt;Card&gt;&gt;.</p><p>The <strong>orElse()</strong> function allows as to generate a default value if any object from the entire flow is missing (we have no account, we have no credit card).</p><p>Comparing the second version of our <strong>ownsMoney</strong> function to the first one, we can see how the Optional objects help us handle possible missing values. We re-wrote the function in an easy to understand statement instead of increasing the complexity with if statements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59a8be471607" width="1" height="1" alt=""><hr><p><a href="https://medium.com/metrosystemsro/java-8-optional-a-practical-use-case-59a8be471607">Java 8 Optional — A practical use case</a> was originally published in <a href="https://medium.com/metrosystemsro">METRO SYSTEMS Romania</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>