<?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 Karol Kisielewski on Medium]]></title>
        <description><![CDATA[Stories by Karol Kisielewski on Medium]]></description>
        <link>https://medium.com/@karolkisielewski?source=rss-c1ec87884e89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uxQw0Byj79varaXb99quzg.jpeg</url>
            <title>Stories by Karol Kisielewski on Medium</title>
            <link>https://medium.com/@karolkisielewski?source=rss-c1ec87884e89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:21:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karolkisielewski/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[Leverage Lambdas for Cleaner Code]]></title>
            <link>https://medium.com/@karolkisielewski/leverage-lambdas-for-cleaner-code-8aff6ed3a1e7?source=rss-c1ec87884e89------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aff6ed3a1e7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[high-order-functions]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Karol Kisielewski]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 10:55:20 GMT</pubDate>
            <atom:updated>2023-02-27T10:55:20.888Z</atom:updated>
            <content:encoded><![CDATA[<p>The post demonstrates a real-life example of Java refactoring aimed at achieving cleaner code and better separation of concerns. The idea originated from my experience with coding in a professional setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMBTbnlqSVabsBcJtSuNng.png" /><figcaption>Generated by Midjourney Bot</figcaption></figure><h3>Once upon a time in a production code</h3><p>When I was working on code persisting some domain data, I ended up with the following:</p><pre>public void processMessage(InsuranceProduct product) throws Exception {<br>    for (int retry = 0; retry &lt;= MAX_RETRIES; retry++) {<br>        try {<br>            upsert(product);<br>            return;<br>        } catch (SQLException ex) {<br>            if (retry &gt;= MAX_RETRIES) {<br>                throw ex;<br>            }<br>            LOG.warn(&quot;Fail to execute database update. Retrying...&quot;, ex);<br>            reestablishConnection();<br>        }<br>    }<br>}<br><br>private void upsert(InsuranceProduct product) throws SQLException {<br>    //content not relevant<br>}</pre><p>The processMessage is a part of a framework contract and is called to persist every processed message. The code performs an idempotent database upsert and handles retry logic in case of errors. The main error I was concerned about was a timed-out JDBC connection that needs to be re-established.</p><p>I wasn’t satisfied with the initial version of processMessage from a clean code perspective. I expected something that would instantly reveal its intent without the need to dive into the code. The method is full of low-level details that need to be understood to know what it does. Additionally, I wanted to separate the retry logic from the database operation being retried to make it easy to reuse.</p><p>Decided to rewrite it to address the mentioned issues.</p><h3>Less procedural, more declarative</h3><p>The first step is to move the updateDatabase() call to a lambda-powered variable. Let the IDE help with that by using <em>Introduce Functional Variable</em> refactoring. Unfortunately, we get an error message:</p><blockquote>No applicable functional interfaces found</blockquote><p>The reason for this is the absence of a functional interface that provides a SAM interface compatible with the upsert method. To address this issue, we need to define a custom functional interface that declares a single abstract method accepting no parameters, returning nothing, and throwing SQLException. Here’s the interface we need to provide:</p><pre>@FunctionalInterface<br>interface SqlRunnable {<br>    void run() throws SQLException;<br>}</pre><p>With the custom functional interface in place, let’s repeat the refactoring. This time, it succeeds. Also, let’s move the variable assignment before the <em>for</em> loop:</p><pre>public void processMessage(InsuranceProduct product) throws Exception {<br>    final SqlRunnable handle = () -&gt; upsert(product);<br>    for (int retry = 0; retry &lt;= MAX_RETRIES; retry++) {<br>        try {<br>            handle.run();<br>            return;<br>        } catch (SQLException ex) {<br>            if (retry &gt;= MAX_RETRIES) {<br>                throw ex;<br>            }<br>            LOG.warn(&quot;Fail to execute database update. Retrying...&quot;, ex);<br>            reestablishConnection();<br>        }<br>    }<br>}</pre><p>Use the <em>Extract Method</em> refactoring to move the <em>for</em> loop and its content to a new method named retryOnSqlException:</p><pre>public void processMessage(InsuranceProduct product) throws Exception {<br>    final SqlRunnable handle = () -&gt; upsert(product);<br>    retryOnSqlException(handle);<br>}<br><br>private void retryOnSqlException(SqlRunnable handle) throws SQLException {<br>    //skipped for clarity<br>}</pre><p>The last step is to use the <em>Inline Variable</em> refactoring to inline the handle variable.</p><p>The final result is below.</p><pre>public void processMessage(InsuranceProduct product) throws Exception {<br>    retryOnSqlException(() -&gt; upsert(product));<br>}</pre><p>The framework entry method now clearly states what it is doing. It is only one line long, so there is no cognitive load.</p><p>The supporting code contains details on how it fulfills its duty and enables reusability:</p><pre>private void retryOnSqlException(SqlRunnable handle) throws SQLException {<br>    for (int retry = 0; retry &lt;= MAX_RETRIES; retry++) {<br>        try {<br>            handle.run();<br>            return;<br>        } catch (SQLException ex) {<br>            if (retry &gt;= MAX_RETRIES) {<br>                throw ex;<br>            }<br>            LOG.warn(&quot;Fail to execute database update. Retrying...&quot;, ex);<br>            reestablishConnection();<br>        }<br>    }<br>}<br><br>@FunctionalInterface<br>interface SqlRunnable {<br>    void run() throws SQLException;<br>}</pre><h3>Conclusion</h3><p>Was it worth the effort? Absolutely. Let’s summarize the benefits.</p><p>The processMessage method now clearly expresses its intent by utilizing a declarative approach with high-level code. The retry logic is separated from the database operation and placed in its own method, which, thanks to good naming, precisely reveals its intent. Furthermore, the lambda syntax allows for easy reuse of the retry feature with other database operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aff6ed3a1e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>