Monday, December 12, 2016

Day 12, Java Holiday Calendar 2016, Avoid Overloading with Lambdas

12. Avoid Overloading with Lambdas

Today's tips is to think twice about the names you assign to you methods that can receives 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.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.