DEV Community

Sergiy Yevtushenko
Sergiy Yevtushenko

Posted on • Edited on

Why use functional style in Java?

While previous post shows how to transform traditional code into functional one, it does not provide answer why it is necessary.

There are several reasons and all of them are important and relevant. I believe that the main reason is the code reliability.

Any approach/tool/methodology/etc. which improves code reliability enables us to create more and more complex systems. This why we adopt every single technology which improves code reliability - testing/static code analyzers/etc.

By using functional style, as shown in previous post, we involve compiler to help cover both, successful and unsuccessful (or null/non-null), outcome of every single intermediate call. As a consequence, compiler helps us to eliminate whole classes of errors, including, for example, NPE. Yes, it still possible to shoot himself in the foot. But this intent must be clearly expressed in code with this approach.

Top comments (2)

Collapse
 
eljayadobe profile image
Eljay-Adobe

For JVM, it will probably be even more beneficial to use Scala (object-oriented programming w/functional-programming support) or Clojure (programmer's programming language w/functional-programming support) to do functional programming.

Because using Java in a functional style isn't the same as using a programming language that has functional-programming support.

Are there any functional-first programming languages for JVM? Something along the lines of Haskell (FP pure), OCaml, or F# (FP impure -aka- FP practical).

Collapse
 
siy profile image
Sergiy Yevtushenko

Of course, there are other languages which might be a better fit for functional programming. In my posts I'm not trying to convince anyone that FP is good, there are many other people who already doing that. Instead I'm trying to show that Java is suitable for FP and use of FP in Java provides a lot of benefits.