Why you should embrace functional programming in Java 8

The functional styles introduced in Java 8 is a big addition to the language. Java is not a pure OOP language anymore, but a hybrid between OOP and functional programming. It's a game changer, and our OOP mindset has to be changed to embrace these changes.

But why should we embrace these changes? Why should we use time and effort getting comfortable with the functional styles when we can solve the problems in pure OOP?

  • The functional styles introduced in Java 8, helps us reduce the gap between the business logic and the code. It allows them to tell the story together in a natural flow on a higher level. Instead of saying how you want things done, you can say what you want done.

  • A lot of boilerplates can be removed, which results in cleaner and more concise code.

  • Higher-order functions allows us to:

    • Send functions into other functions.
    • Create functions inside other functions.
    • Return functions from other functions.

    This is a big win for Java where we had to send, create and return objects to do this job. We will then be able to create code that will be more robust, focused and easier to reuse.

  • Thanks to lambdas, we can now do lazy evaluations. When sending a lambda expression as a method argument, the java compiler will evaluate it when it's called in the method. This is different from normal method arguments, which are evaluated straight away.

  • Lambda makes writing unit tests fun! It allows us to create lightweight unit tests that are clean, small and quick to write. We can stub the code we're testing, using lambdas. This allows us to test how all sorts of scenarios will affect the code.

  • New patterns to explore.

  • And a lot more!

Mastering the new functional styles of Java will be challenging for OOP developers, but it is a challenge that should be very welcome. I would actually go so far and say that you should learn a pure functional programming language. That way you can fully understand the possibilities and power it brings. I think this will help you understand functional programming on another level.

So, embrace functional programming, as well as the good old OOP, and use them together to write even greater code!

Enjoyed the post?

If you don't want to miss future posts, make sure to subscribe