<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Victor Rentea</title>
    <description>The latest articles on DEV Community by Victor Rentea (@victorrentea).</description>
    <link>https://dev.to/victorrentea</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F521917%2Fe4b0de1e-cc05-4ced-b26c-b64983cc512b.jpg</url>
      <title>DEV Community: Victor Rentea</title>
      <link>https://dev.to/victorrentea</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/victorrentea"/>
    <language>en</language>
    <item>
      <title>Presenting Exceptions to Users</title>
      <dc:creator>Victor Rentea</dc:creator>
      <pubDate>Mon, 11 Jan 2021 09:46:46 +0000</pubDate>
      <link>https://dev.to/victorrentea/presenting-exceptions-to-users-1pac</link>
      <guid>https://dev.to/victorrentea/presenting-exceptions-to-users-1pac</guid>
      <description>&lt;p&gt;Many applications have to present the errors that happen in the application to their users in a nice human-readable form. This article covers some widely used best practices on this topic.&lt;/p&gt;

&lt;p&gt;Before we even start, let’s make it clear:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;NEVER expose stack traces in your API responses&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It's not only ugly but dangerous from a security point of view. Based on the line numbers in that stack trace, an attacker might infer the libraries and versions that you're using, and attack you by exploiting their known weaknesses.&lt;/p&gt;

&lt;p&gt;Then what to show our users?&lt;/p&gt;

&lt;h2&gt;
  
  
  Purpose of Exception Message
&lt;/h2&gt;

&lt;p&gt;The simplest idea is to display the exception message string to the users. For simple applications, this might work, but in medium-large applications, two issues arise:&lt;/p&gt;

&lt;p&gt;First, you might want to unit-test that a certain exception was thrown. Asserting message strings will lead to brittle tests, especially when you start adding concatenating user input to those messages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;throw new IllegalArgumentException("Invalid username: " + username);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Secondly, one might argue that you're violating &lt;a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller"&gt;Model-View-Controller&lt;/a&gt;, because you're mixing diverging concerns in the same code: formatting the user-visible message AND detecting the business error condition.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;: Use the exception message to report any technical details about the error that might be useful for developers investigating the exception.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can go as far as to catch an exception in a method &lt;code&gt;x()&lt;/code&gt; and re-throw it back wrapped in another exception with a useful message that captures the key debug information from that method &lt;code&gt;x()&lt;/code&gt;. For example you might include method arguments, any interesting id, current row index, and any other useful debug information. That's the &lt;strong&gt;Catch-rethrow-with-debug-message Pattern&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;throw new RuntimeException("For id: " + keyDebugId, e);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can even instantiate and throw back the same exception type you caught previously. I'm perfectly fine as long as you keep the original exception in the chain by passing it to the new exception constructor as its &lt;code&gt;cause&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Using this pattern will include in your final exception stack trace all the useful debug information you need, allowing you to avoid breakpoint-debugging. 👍 I'll explain more hints on how to avoid breakpointing in a future blog post.&lt;/p&gt;

&lt;p&gt;At the other extreme please don't write 30+ words phrases in your exception messages. They will just distract the reader: their brain will find itself staring endlessly at that nice human-friendly phrase in the middle of that difficult code. And honestly, the exception messages are the least important things to read when browsing unknown code. Keep in mind that the first thing a developer does when debugging an exception is to click through the stack trace. So keep it simple (KISS).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt; Keep your exception messages concise and meaningful. Just like comments.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To sum up, I will recommend that in most cases you keep the exception message for concise debug information for developers' eyes only. User error messages should be externalized in  &lt;code&gt;.properties&lt;/code&gt; files so you can easily adjust, correct, and use UTF-8 accents without any pain.&lt;/p&gt;

&lt;p&gt;But then how to distinguish between different error causes? In other words, what should be the &lt;em&gt;translation key&lt;/em&gt; in that properties file?&lt;/p&gt;

&lt;h2&gt;
  
  
  Different Exception Subtypes
&lt;/h2&gt;

&lt;p&gt;It might be tempting to start creating multiple exception subtypes, one for each business error of our application, and then distinguish between errors based on the exception type. Although fun at first, this will rapidly lead to creating hundreds of exception classes in any typical real-world applications. Clearly, that's unreasonable.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;: Only create a new exception type &lt;code&gt;E1&lt;/code&gt; if you use need to &lt;code&gt;catch(E1)&lt;/code&gt; and selectively handle that particular exception type, to work-around or recover from it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But in most applications, you almost never work-around or recover from exceptions. Instead, you typically terminate the execution of the current use-case/request by allowing the exception to bubble up to the outer layers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Error Code Enum
&lt;/h2&gt;

&lt;p&gt;The best solution to distinguish between your non-recoverable error conditions is using an error code, not the exception message, nor the exception type.&lt;/p&gt;

&lt;p&gt;Should that error code be an &lt;code&gt;int&lt;/code&gt;? If it were, we would need the &lt;em&gt;Exception Manual&lt;/em&gt; at hand every time we walk through the code. Horrible scenario! But wait! &lt;/p&gt;

&lt;p&gt;Every time in Java the range of values is finite and pre-known, we should always consider using an &lt;code&gt;enum&lt;/code&gt;. Let's give it a first try:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MyException&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;RuntimeException&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="no"&gt;GENERAL&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;BAD_CONFIG&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;MyException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Throwable&lt;/span&gt; &lt;span class="n"&gt;cause&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;super&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cause&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;code&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="nf"&gt;getCode&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then every time we encounter an issue due to bad configuration, we could do &lt;code&gt;throw new MyException(ErrorCode.BAD_CONFIG, e);&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Unit tests are also more robust when using &lt;code&gt;enum&lt;/code&gt; for Error Codes, compared to matching the String message:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// junit 4.13 or 5:&lt;/span&gt;
&lt;span class="nc"&gt;MyException&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;assertThrows&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MyException&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;method&lt;/span&gt;&lt;span class="o"&gt;(...));&lt;/span&gt;
&lt;span class="n"&gt;assertThat&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ErrorCode&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;BAD_CONFIG&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getErrorCode&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, we've sorted how to distinguish between errors, and we've mentioned that the user exception messages should be externalized in a &lt;code&gt;.properties&lt;/code&gt; files. But who does and when does this translation? Let's see...&lt;/p&gt;

&lt;h2&gt;
  
  
  The Global Exception Handler
&lt;/h2&gt;

&lt;p&gt;Let's write a GlobalExceptionHandler that catches our exception and translates it into a friendly message for our users. User are typically sending HTTP requests, so we'll assume a REST endpoint in a Spring Boot application, but all other major web frameworks today offer similar functionality.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DGOO7IgW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/0pew55ax1pwbkj145xn9.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DGOO7IgW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/0pew55ax1pwbkj145xn9.jpeg" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@RestControllerAdvice&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;GlobalExceptionHandler&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Logger&lt;/span&gt; &lt;span class="n"&gt;log&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;LoggerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getLogger&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;GlobalExceptionHandler&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;MessageSource&lt;/span&gt; &lt;span class="n"&gt;messageSource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;GlobalExceptionHandler&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageSource&lt;/span&gt; &lt;span class="n"&gt;messageSource&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;messageSource&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;messageSource&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@ExceptionHandler&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MyException&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="nd"&gt;@ResponseStatus&lt;/span&gt; &lt;span class="c1"&gt;// by default returns 500 error code&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;handleMyException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MyException&lt;/span&gt; &lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;HttpServletRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;userMessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;messageSource&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getMessage&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getCode&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getLocale&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;error&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;userMessage&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;userMessage&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The framework will pass to this &lt;code&gt;@RestControllerAdvice&lt;/code&gt; every &lt;code&gt;MyException&lt;/code&gt; that slips from any REST endpoint (&lt;code&gt;@RequestMapping&lt;/code&gt;, &lt;code&gt;@GetMapping&lt;/code&gt;...).&lt;/p&gt;

&lt;p&gt;At this point there's sometimes a debate: where should we translate the error code: on server-side (in Java) or on the browser (in JavaScript)?&lt;/p&gt;

&lt;p&gt;Although it's tempting to throw the problem on the frontend, translating the error codes on the backend tends to localize better the impact of adding a new error code. Indeed, why should the frontend code change when you add or remove a new error?&lt;/p&gt;

&lt;p&gt;Plus, you might even write code to check at application startup that all the enum error codes have a translation in the &lt;code&gt;.properties&lt;/code&gt; files. That's why I will translate the error on the backend and send user-friendly messages in the HTTP responses.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;My Preference&lt;/strong&gt;: translate the error codes on the backend&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I used a Spring &lt;code&gt;MessageSource&lt;/code&gt; to read the user message corresponding to the error code of the caught &lt;code&gt;MyException&lt;/code&gt;. Based on the user Locale, the &lt;code&gt;MessageSource&lt;/code&gt; determines what file to read from, eg: &lt;code&gt;messages_RO.properties&lt;/code&gt; for &lt;em&gt;RO&lt;/em&gt;, &lt;code&gt;messages_FR.properties&lt;/code&gt; for &lt;em&gt;fr&lt;/em&gt;, or default from &lt;code&gt;messages.properties&lt;/code&gt; for any other language. &lt;/p&gt;

&lt;p&gt;I extracted the user Locale from the &lt;em&gt;Accept-Language&lt;/em&gt; header in the HTTP Request. In many applications however, the user language is read from the user profile, instead of the incoming HTTP request.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;src/main/resources/messages.properties&lt;/code&gt; we store the translations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="no"&gt;BAD_CONFIG&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;Incorrect&lt;/span&gt; &lt;span class="n"&gt;application&lt;/span&gt; &lt;span class="n"&gt;configuration&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it! Free internationalization for our error messages.&lt;/p&gt;

&lt;p&gt;There's a minor problem left though. What if we want to report some user input causing the error back to the UI? We need to add parameters to &lt;code&gt;MyException&lt;/code&gt;. After adding other convenience constructors, here's the complete code of it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MyException&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;RuntimeException&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="no"&gt;GENERAL&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;BAD_CONFIG&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// canonical constructor&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;MyException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Throwable&lt;/span&gt; &lt;span class="n"&gt;cause&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;super&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cause&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;code&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;params&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="c1"&gt;// 6 more overloaded constructors for convenience&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ErrorCode&lt;/span&gt; &lt;span class="nf"&gt;getCode&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="nf"&gt;getParams&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will allow us to use those parameters in the &lt;code&gt;messages*.properties&lt;/code&gt; files:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;BAD_CONFIG=Incorrect application configuration. User info: {0}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Oh, and we have to pass those arguments to the &lt;code&gt;MessageSource&lt;/code&gt;when we ask for the translation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;userMessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;messageSource&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getMessage&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getCode&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getParams&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getLocale&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To see the entire app running, checkout &lt;a href="https://github.com/victorrentea/exceptions-guide/commit/7aa14bd5215077a415db4cffb05c3bebb0a7405b"&gt;this commit&lt;/a&gt;, start the &lt;code&gt;SpringBoot&lt;/code&gt; class and navigate to &lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reporting General Errors
&lt;/h2&gt;

&lt;p&gt;When should we use the &lt;code&gt;GENERAL&lt;/code&gt; error code?&lt;/p&gt;

&lt;p&gt;When it comes to what error messages to display to users, many good developers are tempted to distinguish between &lt;strong&gt;as many errors&lt;/strong&gt; they can detect. In other words, they will consider that their users need to be notified about each and every failure cause. Although putting yourself in the shoes of your users is usually a good practice, in this case, it's a trap.&lt;/p&gt;

&lt;p&gt;You should generally prefer displaying an opaque general-purpose error message, like "Internal Server Error, please check the logs". Consider carefully whether the ~developer~ user can do anything about that error or not. If not, do not bother to distinguish that particular error cause, because if you do, you'll have to make sure you continue to detect &lt;strong&gt;that&lt;/strong&gt; error cause from then on. It may be simpler today, but who knows in 3 years... It's a good example of unnecessary and unforeseen long-term maintenance costs.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;: Avoid displaying the exact error cause to your users unless they can do something to fix it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Honestly, if the application configuration is corrupted, can the user really fix that? Probably not. Therefore we should use &lt;code&gt;new MyException(ErrorCode.GENERAL)&lt;/code&gt; or another convenience constructor overload &lt;code&gt;new MyException()&lt;/code&gt; which does the exact same thing.&lt;/p&gt;

&lt;p&gt;We can simplify it even more, and directly &lt;code&gt;throw new RuntimeException("debug message?"...)&lt;/code&gt;. Sonar may not be very happy about it, but it's the simplest possible form.&lt;/p&gt;

&lt;p&gt;But what if there's no additional debug message to add to the new exception? Then your code might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SomeException&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;RuntimeException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that I didn't log the exception before re-throwing. Doing that is actually an anti-pattern, as I will explain in a future blog post.&lt;/p&gt;

&lt;p&gt;But look again at the code snippet above. Why in the world would do you catch that &lt;code&gt;SomeException&lt;/code&gt;? If it were a runtime exception, why don't you let it fly-through? So &lt;code&gt;SomeException&lt;/code&gt; must be a checked exception and you're doing that to convert it into a runtime, invisible one. If that's the case, then you have another widely used option: throw a &lt;code&gt;@SneakyThrows&lt;/code&gt; annotation from Lombok on that method to effectively let the checked exception propagate invisibly down the call stack. You can read more about this technique in &lt;a href="https://victorrentea.ro/blog/hide-checked-exceptions-with-sneakythrows/"&gt;my other blog post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;One last thing: we need to enhance our Global Exception Handler to also catch any other &lt;code&gt;Exception&lt;/code&gt; that slips from a &lt;code&gt;RestController&lt;/code&gt; method, like the infamous &lt;code&gt;NullPointerException&lt;/code&gt;. We need to add another method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@ExceptionHandler&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Exception&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@ResponseStatus&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;handleAnyOtherException&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;HttpServletRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;userMessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;messageSource&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getMessage&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ErrorCode&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;GENERAL&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getLocale&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
    &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;error&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;userMessage&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;userMessage&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that we used a similar code to the previous &lt;code&gt;@ExceptionHandler&lt;/code&gt; method to read the user error messages from the same &lt;code&gt;.properties&lt;/code&gt; file(s). You can do a bit more polishing around, but these are the main points.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusions
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use concise exception messages to convey debugging information for developers&lt;/li&gt;
&lt;li&gt;Catch-rethrow-with-debug-message to display more data in the stack trace&lt;/li&gt;
&lt;li&gt;Only define new exception types in case you selectively catch them&lt;/li&gt;
&lt;li&gt;Use an error code enum to translate errors to users&lt;/li&gt;
&lt;li&gt;If needed, add the incorrect user input in the exception parameters and template your error messages&lt;/li&gt;
&lt;li&gt;We implemented a Global Exception Handler in Spring to catch, log and translate all exceptions slipped from HTTP requests (+internationalized)&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>bestpractices</category>
      <category>java</category>
      <category>cleancode</category>
      <category>exceptions</category>
    </item>
    <item>
      <title>Exceptions and Streams</title>
      <dc:creator>Victor Rentea</dc:creator>
      <pubDate>Tue, 05 Jan 2021 08:45:11 +0000</pubDate>
      <link>https://dev.to/victorrentea/exceptions-and-streams-3m5i</link>
      <guid>https://dev.to/victorrentea/exceptions-and-streams-3m5i</guid>
      <description>&lt;p&gt;&lt;em&gt;About the Author: Victor is a Java Champion and an experienced Independent Trainer, Speaker, and founder of a huge developer community. More on &lt;a href="https://victorrentea.ro"&gt;victorrentea.ro&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This article was first published at &lt;a href="https://victorrentea.ro/blog/exceptions-and-streams/"&gt;Victor's blog&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Java 8 gave us &lt;code&gt;Optional&lt;/code&gt;, a mighty weapon against the most frequent Exception in Java: &lt;code&gt;NullPointerException&lt;/code&gt;. Unfortunately, Java 8 also brought new headaches regarding exceptions, as the default functional interfaces in Java 8 don’t declare throwing any checked exceptions. So every time you get a checked exception within a lambda, you have to fix that somehow.&lt;/p&gt;

&lt;h2&gt;
  
  
  Converting Checked into Runtime Exceptions
&lt;/h2&gt;

&lt;p&gt;The default suggestion offered by most IDEs to auto-fix this issue will produce code like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List&amp;lt;String&amp;gt; dateList = asList("2020-10-11", "2020-nov-12", "2020-12-01");
List&amp;lt;Date&amp;gt; dates = dateList.stream().map(s -&amp;gt; {
   try {
      return format.parse(s);
   } catch (ParseException e) {
      throw new RuntimeException(e);
   }
}).collect(toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Horrible code.&lt;/p&gt;

&lt;p&gt;We could create a dedicated function doing just &lt;code&gt;.parse&lt;/code&gt; and then cast a spell on it with &lt;code&gt;@SneakyThrows&lt;/code&gt;, as we've discussed in &lt;a href="https://dev.tohide-checked-exceptions-with-sneakythrows"&gt;a previous article&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   List&amp;lt;Date&amp;gt; dates = dateList.stream()
        .map(s -&amp;gt; uglyParse(format, s))
        .collect(toList());
   ...
}

@SneakyThrows
private static Date uglyParse(SimpleDateFormat format, String s) {
   return format.parse(s);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But creating this new method just to hack it with Lombok feels wrong. Indeed, we created it for a purely technical reason: to hide the annoying checked exception which doesn't fit with the &lt;code&gt;java.util.Function&lt;/code&gt; interface, which doesn't declare to throw anything.&lt;/p&gt;

&lt;p&gt;Let's play a bit and create a &lt;code&gt;ThrowingFunction&lt;/code&gt; interface declaring to throw any checked exception:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface ThrowingFunction&amp;lt;T,R&amp;gt; {
    R apply(T t) throws Exception;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, our &lt;code&gt;s-&amp;gt;format.parse(s)&lt;/code&gt; expression could be &lt;a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#target-typing"&gt;target-typed&lt;/a&gt; to this new interface, so the following line compiles:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ThrowingFunction&amp;lt;String, Date&amp;gt; p = s -&amp;gt; format.parse(s);
// or
ThrowingFunction&amp;lt;String, Date&amp;gt; p = format::parse;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, the &lt;code&gt;Stream.map()&lt;/code&gt; operation takes a &lt;code&gt;java.util.Function&lt;/code&gt;, you can't change that. But let's imagine we had a function that would take a &lt;code&gt;ThrowingFunction&lt;/code&gt; and return back a 'classic' &lt;code&gt;Function&lt;/code&gt;  that doesn't throw any checked exception anymore.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Function&amp;lt;String, Date&amp;gt; f = wrapAsRuntime(p);
List&amp;lt;Date&amp;gt; dates = dateList.stream().map(f).collect(toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And here's the strange &lt;code&gt;wrapAsRuntime&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static &amp;lt;T,R&amp;gt; Function&amp;lt;T, R&amp;gt; wrapAsRuntime(ThrowingFunction&amp;lt;T, R&amp;gt; p) {
    return t -&amp;gt; {
        try {
            return p.apply(t);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If that's complete nonsense for your, then I would advice that you try to type it yourself. It helps a lot!&lt;/p&gt;

&lt;p&gt;Notice that we’ve used generics to make it highly reusable. That's quite a good idea, isnt'it? It's so good that of course others had it it many years ago... :) &lt;/p&gt;

&lt;p&gt;Introducing the &lt;code&gt;Unchecked.function()&lt;/code&gt; from the &lt;a href="https://github.com/jOOQ/jOOL"&gt;jool library&lt;/a&gt; that does EXACTLY what we did above. Using it, the final code looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Date&amp;gt; dates = dateList.stream().map(Unchecked.function(format::parse)).collect(toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you've been using Java 8 for many years, then this library is a must-have.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Best-practice&lt;/strong&gt;: Whenever checked exceptions are annoying you in lambdas &lt;code&gt;-&amp;gt;&lt;/code&gt; or method references &lt;code&gt;::&lt;/code&gt;, use &lt;code&gt;Unchecked.*&lt;/code&gt; to rethrow it as a &lt;code&gt;RuntimeException&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This doesn't involve any hack in the bytecode (&lt;a href="https://dev.tohide-checked-exceptions-with-sneakythrows"&gt;as @SneakyThrows does&lt;/a&gt;), but only plain java code. Passing a function as a parameter to another function is a very useful practice that I will be blogging about soon, but functions that both take and return functions - those I don't like. It's one of the most complex, hard to read, and especially hard to debug in Java. But since it's a library doing it, and the purpose is obvious, I never hesitated to use it many of my projects.&lt;/p&gt;

&lt;p&gt;Now let's shift a bit the perspective. No matter how you twist it, the processing of the entire stream stops when the first exception is thrown. But what if we don't want to crash but instead collect all the errors.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Try Monad
&lt;/h2&gt;

&lt;p&gt;Let’s change the requirements a bit: we now want to parse all the &lt;strong&gt;valid&lt;/strong&gt; dates and return them IF at least half of them are parseable, otherwise we should throw an exception. This time we can’t let an exception terminate the execution of our stream. Instead, we want to go through all of the items and collect both parsed dates and exceptions. For example, if we are given 3 correctly-formatted dates and 2 invalid ones, we should return the 3 ones that we were able to parse correctly.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Whenever you want to &lt;strong&gt;collect the exceptions&lt;/strong&gt; happening in items, consider using the vavr &lt;code&gt;Try&lt;/code&gt; monad.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;code&gt;Try&amp;lt;&amp;gt;&lt;/code&gt; class from the &lt;a href="https://www.vavr.io/"&gt;vavr library&lt;/a&gt; is a specialization of the &lt;code&gt;Either&amp;lt;&amp;gt;&lt;/code&gt; concept present in many functional programming languages. An instance can store either the result or the occurred exception (if any).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Try&amp;lt;Date&amp;gt;&amp;gt; tries = dateList.stream()
    .map(s -&amp;gt; Try.of(
        () -&amp;gt; format.parse(s) // throwing code
    ))
    .collect(toList());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the &lt;em&gt;throwing code&lt;/em&gt; crashes with an exception, the surrounding &lt;code&gt;Try.of&lt;/code&gt; function will catch that exception and return a &lt;strong&gt;failed Try&lt;/strong&gt;. Therefore, in the &lt;code&gt;tries&lt;/code&gt; list above, there can be items with &lt;code&gt;isSuccess()&lt;/code&gt; either &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;. To count the success ratio, the shortest (geekest) form is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;double successRatio = tries.stream()
    .mapToInt(t -&amp;gt; t.isSuccess() ? 1 : 0)
    .average()
    .orElse(0);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (successRatio &amp;gt; .5) {
    return tries.stream()
        .filter(Try::isSuccess)
        .map(Try::get)
        .collect(toList());
} else {
    throw new IllegalArgumentException("Too many invalid dates");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Problem solved.&lt;/p&gt;

&lt;p&gt;To better understand the code, we can extract a function from it, that returns a &lt;code&gt;Try&amp;lt;&amp;gt;&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static Try&amp;lt;Date&amp;gt; tryParse(SimpleDateFormat format, String s) {
    return Try.of(() -&amp;gt; format.parse(s));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This resembles the style of handling exceptions in other languages like Go and Haskell, which return the exception to their callers.&lt;/p&gt;

&lt;p&gt;By the way, if you think a bit, you could solve the problem without the &lt;code&gt;Try&lt;/code&gt;, by sweeping the data twice: first to count the parseable dates, and then to actually parse them. Or even a single pass using a combination of a &lt;code&gt;.map&lt;/code&gt; returning a &lt;code&gt;null&lt;/code&gt;/&lt;code&gt;Optional.empty&lt;/code&gt; for errors, followed by a &lt;code&gt;.filter&lt;/code&gt;. That could work too, but the &lt;code&gt;Try&lt;/code&gt; approach might be more readable.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Tip&lt;/strong&gt;: Consider &lt;code&gt;*vavr.Try&amp;lt;&amp;gt;&lt;/code&gt; when you want to collect both results and exceptions in a single pass through data.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;By the way, if you keep thinking at the "Monad" word, here’s a nice article to get you past that: &lt;a href="https://dzone.com/articles/functor-and-monad-examples-in-plain-java"&gt;Monads for Java developers&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Disclaimer&lt;/strong&gt;: avoid streaming a large number of items in batch processing. Instead, stick with the industry default: process the data in chunks, and consider introducing Spring Batch for state-of-the-art batches.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusions
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Checked exceptions don't play nice with the Java Stream API.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;@SneakyThrows&lt;/code&gt; (&lt;a href="https://projectlombok.org/features/SneakyThrows"&gt;Lombok&lt;/a&gt;) or &lt;code&gt;Unchecked&lt;/code&gt; (&lt;a href="http://www.jooq.org/products/jOO%CE%BB/javadoc/0.9.5/org/jooq/lambda/Unchecked.html"&gt;jOOL&lt;/a&gt;) to get rid of checked exceptions with Streams&lt;/li&gt;
&lt;li&gt;Consider &lt;code&gt;Try&lt;/code&gt; (&lt;a href="https://www.javadoc.io/doc/io.vavr/vavr/0.10.0/io/vavr/control/Try.html"&gt;vavr&lt;/a&gt;) whenever you want to collect the errors occurring for an element instead of terminating the Stream.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>java</category>
      <category>functional</category>
      <category>cleancode</category>
    </item>
    <item>
      <title>Hide Checked Exceptions with SneakyThrows</title>
      <dc:creator>Victor Rentea</dc:creator>
      <pubDate>Fri, 25 Dec 2020 05:33:28 +0000</pubDate>
      <link>https://dev.to/victorrentea/hide-checked-exceptions-with-sneakythrows-i3h</link>
      <guid>https://dev.to/victorrentea/hide-checked-exceptions-with-sneakythrows-i3h</guid>
      <description>&lt;p&gt;&lt;em&gt;Victor Rentea is a Java Champion and an Independent Trainer with a huge experience on topics like Clean Code, Design Patterns, Unit Testing. Find out more on &lt;a href="https://victorrentea.ro" rel="noopener noreferrer"&gt;victorrentea.ro&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Java is the only programming language in the world that has checked exceptions, which forces the caller to know about the individual exception types thrown by the called function.&lt;/p&gt;

&lt;p&gt;What do you do when you face a checked exception? Propagating checked exceptions through your code is both leaking implementation details, annoying, and even dangerous.  That's why in the vast majority of cases you should catch-rethrow it as a runtime exception, and let it "silently" terminate your current use-case.&lt;/p&gt;

&lt;p&gt;This article introduces a "magic" way to generate that code that we wrote dozens/hundreds of times in our career. Here's a reminder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static Date parseDate(String dateStr) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.parse(dateStr);
    } catch (ParseException e) {
        throw new RuntimeException(e); // this :(
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are sick to do this catch-rethrow manually, here's the &lt;code&gt;@SneakyThrows&lt;/code&gt; annotation coming from the magic realm of the &lt;a href="https://projectlombok.org/features/SneakyThrows" rel="noopener noreferrer"&gt;Project Lombok&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let's just annotate our method with it and simply remove the &lt;code&gt;catch&lt;/code&gt; clause:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@SneakyThrows
public static Date parseDate(String dateStr) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    return format.parse(dateStr);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Doing so will instruct the Lombok annotation processor to hack the bytecode generated by the javac compiler, allowing the code above to compile, although there's no &lt;code&gt;catch&lt;/code&gt;, nor &lt;code&gt;throws&lt;/code&gt; clause for the &lt;code&gt;ParseException&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Warning&lt;/strong&gt;: the Java IDE you use must be hacked (see &lt;a href="https://projectlombok.org/setup/overview" rel="noopener noreferrer"&gt;here&lt;/a&gt; how).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Knowing that Lombok is able to change your code &lt;strong&gt;as it’s compiled&lt;/strong&gt;, one might expect that the current body of our function will be surrounded by&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try { ... } catch (Exception e) { throw new RuntimeException(e); }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s a fair expectation. Indeed, the checked exception is not swallowed but thrown back out of the function.&lt;/p&gt;

&lt;p&gt;However, since Java8, Lombok does it in a bit unexpected way. To see what it really does, let's decompile the &lt;code&gt;.class&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static Date parseDate(String dateStr) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.parse(dateStr);
    } catch (Throwable var6) {
        throw var6;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Indeed, Lombok did add a try-catch block around the body of my function, but it caught a &lt;code&gt;Throwable&lt;/code&gt; and rethrew it without wrapping it at all!&lt;/p&gt;

&lt;p&gt;Something is wrong!&lt;/p&gt;

&lt;p&gt;That &lt;code&gt;Throwable&lt;/code&gt; must have been declared in a &lt;code&gt;throws&lt;/code&gt; clause on the function!&lt;/p&gt;

&lt;p&gt;If you copy-paste the code in a .java file, you’ll quickly see that this code doesn’t compile!! But how was it compiled in the first place?!&lt;/p&gt;

&lt;p&gt;To understand how's that even possible, you have to learn that the distinction between checked and runtime exceptions is only enforced by the Java compiler (javac). The Java Runtime (JVM) does NOT care what kind of exception you throw - it propagates any exception down the call stack the same way. So the Lombok processor tricked javac into producing bytecode that represents code that wouldn’t actually be compilable.&lt;/p&gt;

&lt;p&gt;Panic!&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fd9l65tvt957g47qcycbh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fd9l65tvt957g47qcycbh.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But a minute after you calm down, you get this strange thought: if the checked exception is invisibly thrown, how would you then be able to catch it later? Let's try:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try { 
    parseDate("2020-01-01"); 
} catch (ParseException e) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But this doesn't compile because nothing in the &lt;code&gt;try&lt;/code&gt; block throws a &lt;code&gt;ParseException&lt;/code&gt;. And javac will reject that. See for yourself: &lt;a href="https://github.com/victorrentea/exceptions-guide/commit/aa1ba41cb1b7694ebb087bd405b7580b572b8ab2" rel="noopener noreferrer"&gt;commit&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So what does this mean? It means that the exceptions hidden using &lt;code&gt;@SneakyThrows&lt;/code&gt; aren’t supposed to be caught again individually. Instead, a general &lt;code&gt;catch (Exception)&lt;/code&gt; not ~&lt;code&gt;catch (RuntimeException)&lt;/code&gt;~ should be in place somewhere down the call stack to catch the &lt;em&gt;invisible checked exception&lt;/em&gt;. For example, if you are handling Spring REST endpoint exceptions using &lt;code&gt;@RestControllerAdvice&lt;/code&gt;, make sure you declare to handle &lt;code&gt;Exception.class&lt;/code&gt;. More details in an upcoming &lt;a href="https://dev.topresenting-exceptions-to-users"&gt;article&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Some of you might be disgusted at this point. Others might be super-excited. I’m not here to judge but only to report the techniques that have become wide-spread in the hundreds of projects I trained or consulted for. I agree that this can be misused if careless, so judge whether to use this feature responsibly.&lt;/p&gt;

&lt;p&gt;Okay, okay... But why?!&lt;/p&gt;

&lt;p&gt;Because Java is an old language. 25 years is a long time to carry some baggage. So today Lombok is effectively hacking the language to make us write less and more focused code. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Use Lombok's @SneakyThrows for fatal exceptions that you don't intend to selectively catch.&lt;/li&gt;
&lt;li&gt;Otherwise wrap the checked exceptions in runtime exceptions that you throw instead.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Disclaimer&lt;/strong&gt;: I chose on purpose parsing a date to point out a typically unrecoverable exception. You should definitely use the new Java 8 LocalDate/LocalDateTime API that (surprise!) doesn't throw any more checked exceptions, but runtime ones.&lt;/p&gt;

</description>
      <category>exceptions</category>
      <category>java</category>
      <category>cleancode</category>
      <category>lombok</category>
    </item>
    <item>
      <title>Avoiding NullPointerException</title>
      <dc:creator>Victor Rentea</dc:creator>
      <pubDate>Tue, 15 Dec 2020 20:35:41 +0000</pubDate>
      <link>https://dev.to/victorrentea/avoiding-nullpointerexception-53md</link>
      <guid>https://dev.to/victorrentea/avoiding-nullpointerexception-53md</guid>
      <description>&lt;p&gt;The terrible &lt;code&gt;NullPointerException&lt;/code&gt; (NPE in short) is the most frequent Java exception occurring in production, according to &lt;a href="https://www.overops.com/blog/the-top-10-exceptions-types-in-production-java-applications-based-on-1b-events/"&gt;a 2016 study&lt;/a&gt;. In this article, we’ll explore the main techniques to fight it: the self-validating model and the &lt;code&gt;Optional&lt;/code&gt; wrapper.&lt;/p&gt;

&lt;h2&gt;
  
  
  Self-Validating Model
&lt;/h2&gt;

&lt;p&gt;Imagine a business rule: every Customer has to have a birth date set. There are a number of ways to implement this constraint: validating the user data on the create and update use-cases, enforcing it via &lt;code&gt;NOT NULL&lt;/code&gt; database constraint and/or implementing the null-check right in the constructor of the Customer entity. In this article, we'll explore the last one.&lt;/p&gt;

&lt;p&gt;Here are the 3 most used forms to null-check in constructor today:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public Customer(@NonNull Date birthDate) { // 3
  if (birthDate == null) { // 1
     throw new IllegalArgumentException();
  }
  this.birthDate = Objects.requireNonNull(birthDate); // 2
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above contains 3 &lt;em&gt;alternative&lt;/em&gt; ways to do the same thing, any single one is of course enough:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Classic &lt;code&gt;if&lt;/code&gt; check&lt;/li&gt;
&lt;li&gt;One-liner check using Java 8 &lt;code&gt;java.util.Objects&lt;/code&gt; - most widely used in projects under development today&lt;/li&gt;
&lt;li&gt;Lombok &lt;code&gt;@NonNull&lt;/code&gt; causing an &lt;code&gt;if&lt;/code&gt; check to be added to the generated bytecode.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If there is a setter for the birth date, the check will move there, leaving the constructor to call that setter.&lt;/p&gt;

&lt;p&gt;Enforcing the null-check in the constructor of your data objects has obvious advantages: no one could ever forget to do it. However, frameworks writing directly to the fields of the instance via reflection may bypass this check. Hibernate does this by default, so my advice is to also mark the corresponding required columns as &lt;code&gt;NOT NULL&lt;/code&gt; in the database to make sure the data comes back consistent. Unfortunately, the problem can get more complicated in legacy systems that have to tolerate 'incorrect historical data’.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Trick&lt;/strong&gt;: Hibernate requires a no-arg constructor on every persistent entity, but that constructor can be marked as &lt;code&gt;protected&lt;/code&gt; to hide it from developers.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The moment all your data objects enforce the validity of their state internally, you do get a better night's sleep, but there's also a price to pay: creating dummy incomplete instances in tests becomes impossible. The typical tradeoff is relying more on &lt;a href="https://martinfowler.com/bliki/ObjectMother.html"&gt;Object Mother&lt;/a&gt;s for building valid test objects.&lt;/p&gt;

&lt;p&gt;So, in general, whenever a null represents a data inconsistency case, throw an exception as early as possible.&lt;/p&gt;

&lt;p&gt;But what if that &lt;code&gt;null&lt;/code&gt; is indeed a valid value? For example, imagine our Customer might not have a Member Card because she didn't yet create one or maybe she didn't want to sign up for a member card. We'll discuss this case in the following section.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getters returning Optional
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Best-practice&lt;/strong&gt;: Since Java 8, whenever a function needs to return &lt;code&gt;null&lt;/code&gt;, it should declare to return &lt;code&gt;Optional&lt;/code&gt; instead&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Developers rapidly adopted this practice for functions computing a value or fetching remote data. Unfortunately, that didn't help with the main source of NPEs: our entity model.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A getter for a field which may be &lt;code&gt;null&lt;/code&gt; should return &lt;code&gt;Optional&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Assuming we're talking about an Entity mapped to a relational database, then if you didn't enforce &lt;code&gt;NOT NULL&lt;/code&gt; on the corresponding column, the getter for that field should return &lt;code&gt;Optional&lt;/code&gt;. For non-persistent data objects or NoSQL datastores that don't offer &lt;code&gt;null&lt;/code&gt; protection, the previous section provides ideas on how to enforce null-checks programmatically in the entity code.&lt;/p&gt;

&lt;p&gt;This change might seem frightening at first because we’re touching the 'sacred' getter we are all so familiar with. Indeed, changing a getter in a large codebase may impact up to dozens of places, but to ease the transition you could use the following sequence of safe steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Create a second getter returning &lt;code&gt;Optional&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Optional&lt;/span&gt; &lt;span class="nf"&gt;getMemberCardOpt&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ofNullable&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;memberCard&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Change the original getter to delegate to the new one:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getMemberCard&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;getMemberCardOpt&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;orElse&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Make sure all the Java projects using the owner class are loaded in your workspace.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Inline&lt;/strong&gt; the original getter everywhere. Everyone will end up calling &lt;code&gt;getMemberCardOpt()&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Rename&lt;/strong&gt; the getter to the default name (removing the &lt;code&gt;Opt&lt;/code&gt; suffix)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You're done, with zero compilation failures. After you do this, everyone previously calling the getter will now do &lt;code&gt;getMemberCard().orElse(null);&lt;/code&gt;. In some cases, this might be the right thing to do, as in: &lt;code&gt;dto.phone=customer.getPhone().orElse(null);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;But let's suppose you wanted to use a property of the MemberCard, and you were careful to check for &lt;code&gt;null&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (customer.getMemeberCard() != null) { // Line X
    applyDiscount(order, customer.getMemeberCard().getPoints());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After applying the refactoring steps above, the code gets refactored to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (customer.getMemeberCard().orElse(null) != null) { // Line X
    applyDiscount(order, customer.getMemeberCard().orElse(null).getPoints());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;if&lt;/code&gt; condition can be simplified by using &lt;code&gt;.isPresent()&lt;/code&gt; and the second line by using &lt;code&gt;.get()&lt;/code&gt;. Then one could even shorten the code to a single line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;customer.getMemberCard().ifPresent(card -&amp;gt; applyDiscount(order, card.getPoints()));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means that you still need to go through all the places the getter is called to &lt;em&gt;improve&lt;/em&gt; the code as we saw above. Furthermore, I bet that in large codebases you'll also discover places where the null-check (// Line X) was forgotten because the developer was tired/careless/rushing back then:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;applyDiscount(order, customer.getMemeberCard().orElse(null).getPoints());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Tip&lt;/strong&gt;: IntelliJ will hint you at the possible NPE in this case, so make sure the inspection 'Constant conditions and exceptions' is turned on.&lt;/p&gt;

&lt;p&gt;Signaling the caller at compile-time that there might be nothing returned to her is an extremely powerful technique that can defeat the most frequent bug in Java applications. Most NPEs occur in large projects mainly because developers aren’t fully aware some parts of the data might be &lt;code&gt;null&lt;/code&gt;. It happened on our project: we discovered dozens of &lt;code&gt;NullPointerExcepton&lt;/code&gt;s just waiting to happen when we moved to &lt;code&gt;Optional&lt;/code&gt; getters.&lt;/p&gt;

&lt;h4&gt;
  
  
  Frameworks and Optional getters
&lt;/h4&gt;

&lt;p&gt;Would frameworks allow getters to return Optional?&lt;/p&gt;

&lt;p&gt;First of all, to make it clear, we only changed the return type of the getter. The setter and the field type kept using the raw type (not &lt;code&gt;Optional&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;All modern object-mapper frameworks (eg Hibernate, Mongo, Cassandra, Jackson, JAXB ...) can be instructed to read from private fields via reflection (Hibernated does it by default). So really, the frameworks don’t care about your getters.&lt;/p&gt;

&lt;h4&gt;
  
  
  When is Optional overkill?
&lt;/h4&gt;

&lt;p&gt;You should consider making null-safe the objects you write logic on: Entities and Value Objects. As I explained in my &lt;a href="https://www.youtube.com/watch?v=tMHO7_RLxgQ&amp;amp;list=PLggcOULvfLL_MfFS_O0MKQ5W_6oWWbIw5&amp;amp;index=3"&gt;Clean Architecture talk&lt;/a&gt;, you should avoid writing logic on API data objects (aka Data Transfer Objects). Since no logic uses them, null-protection is overkill.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Use &lt;code&gt;Optional&lt;/code&gt; in your Domain Model not in your DTO/API Model.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Pre-instantiate sub-structures
&lt;/h2&gt;

&lt;p&gt;Never do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private List&amp;lt;String&amp;gt; labels;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Always initialize the collection fields with an empty one!&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private List&amp;lt;String&amp;gt; labels = new ArrayList&amp;lt;&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Those few bytes allocated beforehand almost never matter. On the other hand, the risk of doing &lt;code&gt;.add&lt;/code&gt; on a &lt;code&gt;null&lt;/code&gt; list is just too dangerous. In some other cases, you might want to make the field &lt;code&gt;final&lt;/code&gt; and take it via the constructor. Never leave collections references to have a &lt;code&gt;null&lt;/code&gt; value.&lt;/p&gt;

&lt;p&gt;Many teams choose to decompose larger entities into smaller parts. When those parts are mutable, make sure you instantiate the parts in the parent entity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private BillingInfo billingInfo = new BillingInfo();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would allow the users of your model to do &lt;code&gt;e.getBillingInfo().setCity(city);&lt;/code&gt; without worrying about nulls.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;You should consider upgrading your entity model to either reject a &lt;code&gt;null&lt;/code&gt; via self-validation or present the nullable field via a getter that returns &lt;code&gt;Optional&lt;/code&gt;. The effort of changing the getters of the core entities in your app is considerable, but along the way, you may find many dormant NPEs.&lt;/p&gt;

&lt;p&gt;Lastly, always instantiate embedded collections or composite structures.&lt;/p&gt;

&lt;h2&gt;
  
  
  More from me
&lt;/h2&gt;

&lt;p&gt;In case you liked this article, follow me on social media or check out &lt;a href="https://victorrentea.ro"&gt;my website&lt;/a&gt; for more.&lt;/p&gt;

</description>
      <category>java</category>
      <category>exceptions</category>
      <category>bestpractices</category>
    </item>
  </channel>
</rss>
