Functional Programming in Java

Stream and Optional classes - added to Java 8 - allow you to have some fun with functional programming. The problem is Java still misses quite a lot to be taken as a serious FP language. Lambda notation and two monads (Optional and Stream) are just the tip of the iceberg. This leads to arising of libraries like vavr or functionaljava - both deriving from purely functional language Haskell.

One of the first things you need to get rid of when trying to be more functional, is the attempt to unwrap the monad too early. It usually involves using methods like Optional.get() or Stream.collect() where there is yet no need. Sometimes though, Java doesn't help with that, so let me give you some custom code for the rescue.

In this article, I am going to present you a simple trick that will make using java.util.function.Function.andThen() more useful. 

As an example I will use ExternalSystemGateway class, which job is to call external system along with serializing/mapping the messages:

You can see that every line of the invoke method does some kind of action, which transforms some input type to another output type.
1

Checked exceptions & Java 8

Defining custom exceptions (both checked and unchecked) is a common approach to handling errors in Java applications. It usually leads to creating a new class for every different type of error, marking methods with throws keyword or wrapping code with try-catch blocks. This can lead to the code which is hard to read since every block adds another level of complexity. 

Lambdas in Java 8 started the boom for functional approach in writing the code.
1
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.