Search code examples
performancejava-8bigdecimalsoftware-quality

How to avoid of huge if condition using BigDecimals?


I've working on bank institution and I need to perform transactions like deposit, withdraw, transfer etc. And when we are considering fields with big values, I saw that it is common use BigDecimal with Java 8 in a Spring Boot application.

When I have to compare if that number (BigDecimal) is it is greater or smaller than other I've learned that we need to use compareTo() method. In my example I need to sum two values and compare the result with the third number, as I am sharing in the following example, using Java 8 and BigDecimal:

if ((request.getTransactionValue().add(BigDecimal.valueOf(totalTransactionValuePerDay))).compareTo(accountBank.getWithdrawLimitPerDay())
    > 0) {
            throw new UnprocessableEntityException("Withdraw limit per day has exceeded"); 
}

But thinking of clean, maintainable and understandable code, can someone, please, share a better approach such as concise and/or intelligent solution?

It is a validation to check if the customer achieves the limit of withdraw per day in a transaction bank. I am wondering how to work with BigDecimal using Java 8 or 11 without this huge if condition.

Another approach could be using a verbose code but before this I hope to find out or get help to code better.

Feel free to check my complete code here.


Solution

  • A conditional may be looking longer for you now (with only 3 variables! in hand). But it definitely gets larger when you want to add n BigDecimals and compare them to your data.

    As Nikolas has answered already, one immediate intuition is to move them to separate methods, perform operation there and return the required value back to the caller.

    Other very simple implementation would be to use reduce operation as shown below (Handy to add multiple values in particular, better readability too IMO),

    BigDecimal bigDecimal1 = new BigDecimal(1);
    BigDecimal data = new BigDecimal(3);
    
    Stream.of(bigDecimal1, BigDecimal.valueOf(2)) // Can be generalised/refactored as a Function<Stream<BigDecimal>, BigDecimal> 
        .reduce(BigDecimal.ZERO, BigDecimal::add) // Identity for sum, and Accumulator.
        .compareTo(data));