Java 8 approach to solve If-else ladder.
if else ladder in java

Java 8 approach to solve If-else ladder.

Consider a typical system where you have to calculate prices of certain goods based on type of customer persona ; this is use case of using if else blocks which increase the moment we want to add more conditions.

Although there are different approaches to solve this type of problems but today we are going looking into how we can create validation based on Java 8 functional interface like Function and Predicate.

Sample Problem : We have to calculate the discount for every individual user types , ex: User with the type GOLD subscription gets 25% discount for the cart value.

Take a look the sample below to understand how it can be done using traditional if-else ladder.

Traditional if-else ladder

The above works fine but the moment we have to add more checks the function started growing.

To solve the above problem we can use Java 8 functional interface, definition mentioned below -

Function<T, R> 
- * @param t the function argument * @return the function result        

This Function<T, R> act as type as a discount calculator for us.

Predicate<T> - * @param t the input argument        

This Predicate type works for us as replacement for user type condition

Let's look how the replacement condition looks.

if(cart.getUserType().equals("SILVER"))

This condition replceed by Predicate 

Predicate<Cart> CART_SILVER = cart -> cart.getUserType().equals("SILVER");        

Similarly replacement of discount calculation -

return cart.getBillAmount()*0.15;

This statement replaced by Function

Function<Cart, Double> DISCOUNT_15 = cart -> cart.getBillAmount()*0.15;        

Now we create Map of this to condition along with method which accept cart object return Function type on which we can apply for cart object : see the below snapshot

Map used for cart rules definition.

Now for every cart item we can calculate discount by calling this CartRules method -

Object discount = CartRules.getRuleFor(cart).apply(cart);        

Do check this code on GitHub repo :

Github Repository for above code

Thanks for reading !!

要查看或添加评论,请登录

Deepak Sharma的更多文章

  • Sentiment analysis of whatsapp chat using R.

    Sentiment analysis of whatsapp chat using R.

    Yes !! this is possible with the help of language using R. Here we are going to talk about how we could do the…

    2 条评论

社区洞察

其他会员也浏览了