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
Please enter at least three characters to search
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

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

  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • Data Quality: A Novel Perspective for 2025
  • Orchestrating Microservices with Dapr: A Unified Approach
  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
Likes (4)
Comment
Save
Tweet
Share
7.0K 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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!