DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • How To Work Effectively With JDBC in Java Scripts
  • Getting Started With HarperDB and Java: Your First "Hello, World" Integration
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • The First Annual Recap From JPA Buddy

Trending

  • How to Submit a Post to DZone
  • Applying the Pareto Principle To Learn a New Programming Language
  • Spring AI: How To Write GenAI Applications With Java
  • Integration Testing With Keycloak, Spring Security, Spring Boot, and Spock Framework
  1. DZone
  2. Data Engineering
  3. Databases
  4. Leverage Lambdas for Cleaner Code

Leverage Lambdas for Cleaner Code

Let's demonstrate a real-life example of Java refactoring aimed at achieving cleaner code and better separation of concerns.

By 
Karol Kisielewski user avatar
Karol Kisielewski
·
Feb. 26, 23 · Tutorial
Like (4)
Save
Tweet
Share
6.5K Views

Join the DZone community and get the full member experience.

Join For Free

This article 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.

Once Upon a Time in a Production Code

When I was working on code persisting some domain data, I ended up with the following:

Java
 
public void processMessage(InsuranceProduct product) throws Exception {
    for (int retry = 0; retry <= MAX_RETRIES; retry++) {
        try {
            upsert(product);
            return;
        } catch (SQLException ex) {
            if (retry >= MAX_RETRIES) {
                throw ex;
            }
            LOG.warn("Fail to execute database update. Retrying...", ex);
            reestablishConnection();
        }
    }
}

private void upsert(InsuranceProduct product) throws SQLException {
    //content not relevant
}

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.

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.

I decided to rewrite it to address the mentioned issues.

Less Procedural, More Declarative

The first step is to move the updateDatabase() call to a lambda-powered variable. Let the IDE help with that by using Introduce Functional Variable refactoring. Unfortunately, we get an error message:

No applicable functional interfaces found

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:

Java
 
@FunctionalInterface
interface SqlRunnable {
    void run() throws SQLException;
}

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 for loop:

Java
 
public void processMessage(InsuranceProduct product) throws Exception {
    final SqlRunnable handle = () -> upsert(product);
    for (int retry = 0; retry <= MAX_RETRIES; retry++) {
        try {
            handle.run();
            return;
        } catch (SQLException ex) {
            if (retry >= MAX_RETRIES) {
                throw ex;
            }
            LOG.warn("Fail to execute database update. Retrying...", ex);
            reestablishConnection();
        }
    }
}

Use the Extract Method refactoring to move the for loop and its content to a new method named retryOnSqlException:

Java
 
public void processMessage(InsuranceProduct product) throws Exception {
    final SqlRunnable handle = () -> upsert(product);
    retryOnSqlException(handle);
}

private void retryOnSqlException(SqlRunnable handle) throws SQLException {
    //skipped for clarity
}

The last step is to use the Inline Variable refactoring to inline the handle variable.

The final result is below.

Java
 
public void processMessage(InsuranceProduct product) throws Exception {
    retryOnSqlException(() -> upsert(product));
}

The framework entry method now clearly states what it is doing. It is only one line long, so there is no cognitive load.

The supporting code contains details on how it fulfills its duty and enables reusability:

Java
 
private void retryOnSqlException(SqlRunnable handle) throws SQLException {
    for (int retry = 0; retry <= MAX_RETRIES; retry++) {
        try {
            handle.run();
            return;
        } catch (SQLException ex) {
            if (retry >= MAX_RETRIES) {
                throw ex;
            }
            LOG.warn("Fail to execute database update. Retrying...", ex);
            reestablishConnection();
        }
    }
}

@FunctionalInterface
interface SqlRunnable {
    void run() throws SQLException;
}

Conclusion

Was it worth the effort? Absolutely. Let’s summarize the benefits.

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.

Database Integrated development environment Java Database Connectivity Java (programming language) AWS Lambda code style

Opinions expressed by DZone contributors are their own.

Related

  • How To Work Effectively With JDBC in Java Scripts
  • Getting Started With HarperDB and Java: Your First "Hello, World" Integration
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • The First Annual Recap From JPA Buddy

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: