On StackOverflow I found multiple advices to stick with BigDecimal in Java instead of reinventing the wheel.

Despite that, I decided to create my custom class, and I would ask if that was a good idea and pros or cons about my design in comparsion to BigDecimal. The reasons to choose custom implementation and characteristic of my design are:

  • no double/float constructors like in BigDecimal (risk of mistake) - long internally with 8 decimal places - this restrics min/max to ~10 bilion but system is cryptocurrency-targeted so typical values are small.
  • no difference in "0.0" and "0.00" as BigDecimal have
  • simple SQL compatibility by BIGINT column
  • hard connection to currency object/code - cannot create amount wihtout currency and also cannot do arthimethic/comparsion of two values in different currencies
  • Control of creation possible values to not overflow long (-10 bilion to 10 bilion)
  • internal overflow protection on computations

Do you think that those reasons as good to choose custem implementation instead of BigDecimal?

To minimize risks I have cover very lot of situations by unit test and also use BigDecimal for initial conversion from string:

BigDecimal decimal = new BigDecimal(value);
... check MIN/MAX allowed values ...
BigDecimal multiplied = decimal.multiply(new BigDecimal(String.valueOf(DECIMAL_DIVIDER)));
long internalResult = multiplied.toBigInteger().longValue();
return new Amount(internalResult, cryptoCurrency.getInternalCode());

Your reasons for creating a custom class are perfectly valid. If your system was only working with a single currency, the argument for creating a custom class would be much weaker. But with multiple currencies, I think a custom class is almost a must.

Note that your custom class could use a BigDecimal internally to hold the amount, if it was a good match for what you actually need to do. If a long matches your model better, then go ahead with that.

  • 2
    A similar approach - Quantity and specifically a use-case of Money - shows up in Martin Fowler's Patterns of Enterprise Application Architecture. He briefly addresses the value of this approach in a system without multiple currencies and also has some code snippets suggesting useful additional methods you might want to add. – combinatorics Feb 10 '14 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.