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