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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

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

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Hints for Unit Testing With AssertJ
  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java

Trending

  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  1. DZone
  2. Coding
  3. Java
  4. Lambdas and Clean Code

Lambdas and Clean Code

As with the introduction of any new tool, Java 8's lambda expressions have led to odd biases and poor use. Here are some considerations to keep your code clean.

By 
Nicolas Fränkel user avatar
Nicolas Fränkel
DZone Core CORE ·
Sep. 26, 17 · Tutorial
Likes (109)
Comment
Save
Tweet
Share
33.8K Views

Join the DZone community and get the full member experience.

Join For Free

As software developers, we behave like children. When we see shiny new things, we just have to play with them. That’s normal, accepted, and in general, even beneficial to our job… up to a point.

When Java started to provide annotations with version 5, there was a huge move toward using them. Anywhere. Everywhere. Even when it was not a good idea to do that. But it was new, hence it had to be good. Of course, when something is abused, there’s a strong movement against it — so that even when the usage of annotations may make sense, some developers might strongly be against it. There’s even a site about that (warning, trolling inside).

Unfortunately, we didn’t collectively learn from overusing annotations. With a lot of companies having migrated to Java 8, one starts to notice a lot of code making use of lambdas like this one:

List<Person> persons = ...;
persons.stream().filter(p -> {
    if (p.getGender() == Gender.MALE) {
        return true;
    }
    LocalDate now = LocalDate.now();
    Duration age = Duration.between(p.getBirthDate(), now);
    Duration adult = Duration.of(18, ChronoUnit.YEARS);
    if (age.compareTo(adult) > 0) {
        return true;
    }
    return false;
}).map(p -> p.getFirstName() + " " + p.getLastName())
  .collect(Collectors.toList());


This is just a stupid sample, but it gives a good feeling of the code I sometimes have to read. It’s, in general, longer and even more convoluted, or to be politically correct, it has room for improvement — a lot of room.

The first move would be to apply correct naming, as well as to move the logic to where it belongs to.

public class Person {

    // ...

    public boolean isMale() {
        return getGender() == Gender.MALE;
    }

    public boolean isAdult(LocalDate when) {
        Duration age = Duration.between(birthDate, when);
        Duration adult = Duration.of(18, ChronoUnit.YEARS);
        return age.compareTo(adult) > 0;
    }
}


This small refactoring already improves the readability of the lambda:

persons.stream().filter(p -> {
    if (p.isMale()) {
        return true;
    }
    LocalDate now = LocalDate.now();
    if (p.isAdult(now)) {
        return true;
    }
    return false;
}).map(p -> p.getFirstName() + " " + p.getLastName())
        .collect(Collectors.toList());


But it shouldn’t stop there. There’s an interesting bias regarding lambda: They have to be anonymous. Nearly all examples on the web show anonymous lambdas. But nothing could be further from the truth!

Let’s name our lambdas and check the results:

// Implementation details
Predicate<Person> isMaleOrAdult = p -> {
    if (p.isMale()) {
        return true;
    }
    LocalDate now = LocalDate.now();
    if (p.isAdult(now)) {
        return true;
    }
    return false;
};
Function<Person, String> concatenateFirstAndLastName = p -> p.getFirstName() + " " + p.getLastName();

// Core
persons.stream().filter(isMaleOrAdult).map(concatenateFirstAndLastName)


Nothing mind-blowing. Yet, notice that the stream itself (the last line) has become more readable, not hidden behind implementation details. It doesn’t prevent developers from reading them, but only if necessary.

Tools are tools. Lambdas are just one of them in a Java developer’s toolbelt. But concepts are forever.

Java (programming language) Coding best practices

Published at DZone with permission of Nicolas Fränkel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Hints for Unit Testing With AssertJ
  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java

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!