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.
Functional programming in Java — Replace traditional if-else blocks with Maps and Streams
Lengthy if-else blocks are developers nightmare and hard to maintain with full of side effects.Sonar rightly flags such code blocks as ‘Cognitive complexities’. Yes, it is.
Introduction of Functional interface in Java 8 paved way for first-class functions.This is very useful when paired with predicates to replace traditional if-else blocks
Example — If-else block
We can translate the above if-else code block into a rule matrix with the help of predicates and functions. If statements can be converted into predicates and corresponding rules executed can be converted…
Backend Java developer