JavaMoney / jsr354-ri

JSR 354 - Moneta: Reference Implementation
Other
344 stars 101 forks source link

Why Monetary classes are closed to extension? / formatting with fractional digits #324

Closed piotr-wysz closed 4 years ago

piotr-wysz commented 4 years ago

Hi, @stokito I am repeating the topic that I added under wrong project.

Is there any reason why classes Money, FastMoney, RoundedMoney are declared as final? I wanted to change behavior of one method in Money class but it's not possible. Security reasons are not relevant here because one can still implement MonetaryAmount interface and for example do it wrongly and cause some issues. IMHO the code should be open for extension (and closed for modification). It's just a question if there are any reasons to keep these classes as final?

Why I need to extend Money class is that in the project I work on there's Money in many places that is passed to bodies as String in rest services. The problem is that the money has to always be in format with two fractional digits. For example calling Money.of(new BigDecimal("10"), "GBP").toString() will result in "GBP 10", while what I need is "10.00". I can solve it by doing as below: Money.of(new BigDecimal("10"), "GBP").getNumberStripped().setScale(2, RoundingMode.HALF_EVEN).toString() result of this expression will be what I need "10.00".

I tried using MonetaryAmountFormat but it's not suitable for me (I think) because it's bound with Locale, so adding for example UK or US adds commas for example "10,000.00" when I need "10000.00". Even when I provided custom template the number was formatted with commas.

So best option would be to overide "toString" from Money object. Then every time when in my project the Money is converted to string the value would be formatted as I intend.

I would be glad if you know better way of achieving this.

The point about Money being value object like Integer and should be immutable is valid, I agree with that.

Thanks a lot!

keilw commented 4 years ago

They are modeled after classes like Integer or Long, so yes, that is why they are final and we are unlikely to change that.