3

I am learning the Java 8 syntax and came across a piece of code in our application below in an interface:

default EmployeeEnricher employeeEnricher() {
      return builder -> {
          return;
      };
}

Can someone please help me understand what the above syntax means?

There are multiple implementations of this method in the application, each with its own logic.

Lii
  • 11,553
  • 8
  • 64
  • 88
user1318369
  • 715
  • 5
  • 15
  • 34
  • 2
    It returns an instance of `EmployeeEnricher` which we can assume is a `FunctionalInterface` (can be represented as a lambda). It would seem this one is akin to a `Consumer` where the T is whatever that builder variable is. Lambda don't have to be passed to methods, they can be assigned to variables or just outright declared, as they are a value (not a statement themselves). – Rogue Feb 24 '19 at 21:31
  • 4
    Like with ordinary methods, such an explicit `return;` is not necessary, so `builder -> {}` would do, which would emphasize that this `EmployeeEnricher` simply does nothing. – Holger Feb 25 '19 at 09:17

1 Answers1

5

It just returns an EmployeeEnricher which basically is a Consumer<Builder> (or a functional interface from the same kind) which does nothing with its parameter meaning that if the class implementing the interface doesn't @Override this method, this will become its default behaviour (meaning nothing will happen).

In your application, you'll encounter different types of employees probably which will be enriched in different manners using a builder given in parameter using employeeEnricher().accept(builder)

This means implementation can mean two things for me :

  • Either the design is poor, and all employees should have their own implementation, meaning this interface's method should not have be default but simply a classic abstract method of the interface

  • Either some employees do not get enriched in the context of your application, and thus this method offers a default implementation making sense

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89