Home > Blockchain >  What can be a good solution to strengthen this multiply() BigDecimal operation in order to handle th
What can be a good solution to strengthen this multiply() BigDecimal operation in order to handle th

Time:03-10

in my code I have the following code involving a multiply() operation on twoBigDecimal values

walletsDTOList.stream().forEach( (WalletDTO wallet) -> {
    try {
        ConversionPriceDTO conversionPriceDTO = coingeckoInfoService.getCoinPrice(wallet.getCoin().getName(),targetCurrency);
        BigDecimal conversionRate = conversionPriceDTO.getPrice();
        conversionPriceDTO.setPrice(wallet.getAmount().multiply(conversionRate));
        wallet.setConvertedCurrencyAmountInfo(conversionPriceDTO);
    } catch (JsonProcessingException | BindingException e) {
        throw new RuntimeBindingException(e.getMessage());
    }
});

This line:

conversionPriceDTO.setPrice(wallet.getAmount().multiply(conversionRate));

Now my problem is that the wallet.getAmount() coming from the DB and it could be NULL. The problem is that in case of NULL value I obtain the following exception:

java.lang.NullPointerException: Cannot invoke "java.math.BigDecimal.multiply(java.math.BigDecimal)" because the return value of "com.easydefi.users.dto.WalletDTO.getAmount()" is null

I need to toughen up this operation. For my NULL value equals to 0 so in this case the multiply operation must return 0.

What can be a smart way to do it? My idea was to put the previous line (containing the multiply() operation) into a try catch and in case of NullPointerException set 0.

Is it good or can I do better?

CodePudding user response:

If you encounter a different NPE in the same block of code, catching it and assuming that it was thrown because getAmount returned null will hide some other bug.

Either change getAmount to never return null, or do something like:

final BigDecimal walletAmount = wallet.getAmount();
conversionPriceDTO.setPrice(
        walletAmount == null ? BigDecimal.ZERO
                             : walletAmount.multiply(conversionRate)
);

CodePudding user response:

Something like this may help:

final BidDecimal amount = Optional.ofNullable(wallet.getAmount()).orElse(BigDecimal.ZERO);
...
  • Related