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

Related

  • Hints for Unit Testing With AssertJ
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • Rethinking Java CRUDs With Event Sourcing and CQRS Patterns
  • Detecting Bugs and Vulnerabilities in Java With SonarQube

Trending

  • Integrating AI-Driven Decision-Making in Agile Frameworks: A Deep Dive into Real-World Applications and Challenges
  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  • Spec-Driven Integration: Turning API Sprawl Into a Governed Capability Fleet for AI
  • Product-Led Software Delivery: Intelligent Platforms for DevOps at Scale
  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
·
Sep. 26, 17 · Tutorial
Likes (109)
Comment
Save
Tweet
Share
34.1K 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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Hints for Unit Testing With AssertJ
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • Rethinking Java CRUDs With Event Sourcing and CQRS Patterns
  • Detecting Bugs and Vulnerabilities in Java With SonarQube

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook