Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Holiday Calendar 2016 (Day 12): Avoid Overloading With Lambdas

DZone's Guide to

Java Holiday Calendar 2016 (Day 12): Avoid Overloading With Lambdas

Lambdas are fantastic, but their popularity might lead to sloppy use. Naming them after specific uses keeps both the compiler and the client happy.

· Java Zone
Free Resource

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.


Image title

Today's tip is to think twice about the names you assign to you methods that can receive lambdas — and avoid letting them share the same name.

If there are two or more methods with the same name that take functional interfaces as parameters, then this would likely create a lambda ambiguity on the client side. For example, if there are two Point methods, add(Function<Point, String> renderer) and add(Predicate<Point> logCondition), and we try to call point.add(p -> p + “lambda”) from the client code, the compiler is unable to determine which method to use and will produce an error. Instead, consider naming methods according to their specific use.

I have contributed a lot to the open-source stream based ORM project Speedment, and there we have used this naming convention, allowing lambdas to be used in a good way throughout the API.

Do This

public interface Point {
    addRenderer(Function<Point, String> renderer);
    addLogCondition(Predicate<Point> logCondition);
}


Don't Do This

public interface Point {
    add(Function<Point, String> renderer);
    add(Predicate<Point> logCondition);
}


Read more on Java 8 API design principles on DZone here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Moving towards a private or Hybrid cloud infrastructure model? Get started with our OpenStack Deployment Models guide to learn the proper deployment model for your organization.

Topics:
java ,lambdas ,naming convention ,functional interface

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}