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());
Best Answer
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.