Functional Programming in Java — Replacing if-else-if ladder with vavr match case logic

Prince Solomon S
2 min readMay 17, 2021

In my previous story , I tried converting an if-else-if block into rule matrix by mapping Predicates and Functions. Even-though we broke through the wall of imperative programming, the rule matrix approach is complex and its difficult for the developers to hop around various classes for understanding a simple logic.

To make our life easier, we are going to use Java’s functional library vavr to replace if-else-if ladder with vavr’s match cases

Let’s consider the below if-else-if code block to calculate total amount based on cart’s value. With more discounts to come this block will become a tall ladder soon.

Cart value if-else block

Lets add vavr dependency to pom.xml

Now lets convert the if-else-if block into vavr’s match case. It looks similar to switch-case statement.

Match-Case block

Match— Receives the value which needs to be compared

Case(Predicate,Return value) — Maps predicate with value to be returned

Predicate $(value) — This is similar to equals

Predicate $() — This is similar to switch-case’s default block

The above block doesn’t handle null checks so we can make use of Option API of vavr library to perform null checks

Null checks and validation using Vavr’s Option API

Option.of() — Returns non-nullable value of cart object. We can chain it with filter to eliminate empty cart and then we can map it to the Match-Case function which will return total cost based on cart’s value.

getOrElse(value) — Similar to Optional.orElse().This will return value for filtered null or empty cart

Vavr does the heavy-lifting in implementing functional programming paradigm in Java by eliminating side-effects which will benefit in writing effective test cases around business logic.

We will continue to explore various features in Vavr library in days to come.

--

--