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


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.

Topics:
java ,lambdas ,naming convention ,functional interface

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}