Java – Is Using Lambda Expressions Good Practice?

javalambda

I have recently mastered the Lambda expression that was introduced in java 8. I find that whenever I am using a functional interface, I tend to always use a Lambda expression instead of creating a class that implements the functional interface.

Is this considered good practice? Or are their situations where using a Lambda for a functional interface is not appropriate?

Best Answer

There are a number of criteria that should make you consider not using a lambda:

  • Size The larger a lambda gets, the more difficult it makes it to follow the logic surrounding it.
  • Repetition It's better to create a named function for repeated logic, although it's okay to repeat very simple lambdas that are spread apart.
  • Naming If you can think of a great semantic name, you should use that instead, as it adds a lot of clarity to your code. I'm not talking names like priceIsOver100. x -> x.price > 100 is just as clear as that name. I mean names like isEligibleVoter that replace a long list of conditions.
  • Nesting Nested lambdas are really, really hard to read.

Don't go overboard. Remember, software is easily changed. When in doubt, write it both ways and see which is easier to read.