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

Traditional if-else blocks. Additional conditions might mess up this

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 into functions. Then we can map predicates with functions to produce a rule matrix.

RuleMatrix — Utility class with rulesMap mapping Predicate with Function.

getRule method defined in the above class will receive an object Cart and returns the corresponding function to be applied on it by filtering the rulesMap with predicate.

Functions and Predicates can be defined as constants in separate classes which will be helpful in scaling up the rules.

CartFunctions — collection of function to be applied on a cart
CartPredicates — collection of predicates for cart

Using this rule matrix is very simple— fetch the rules (i.e corresponding function) and apply it on the cart. Goodbye to complex code blocks!!

RuleMatrix.getRule(cart6).apply(cart6)
main method — constructed a cart object and used rule matrix to apply corresponding function

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store