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());