Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubles with constraints in Java?

Tags:

java

I am porting a legacy Python system to Java. I'm a python developer primarily so this question concerns how I might take an unsatisfactory pattern in the original Python system but do it better in my Java version.

A system I'm working on deals with prices of products. All products have prices > 0.0.

In the orginal system all prices are represented as Python float objects (roughly like a Java Double). Functions which operate on these prices typically begin with a bunch of asserts to check that the range of the prices are sensible. Since there are a lot of functions there are a lot of assertions which become very repetitive after a while.

These assertions are better than nothing but it would be far better to throw an error the instant that something tried to create a negative price, since that's where the fault lies.

It occurred to me that I might do better in my re-implementation by inventing a new type of numberish thing which behaves exactly like a Double in all ways except that it cannot be constructed with a negative value. If I had such an object then I could rely on Java's type system and not need to write so many asserts.

Other than that (to begin with) it will obey all the normal rules of arethmatic - it will be a subclass of Double.

Later on I might extend this class by adding features that embrace more features of real-world money, e.g. preventing fractions of pennies. That's not actually needed in my initial version, but I'd like any pattern I adopt to accomodate this sort of development over the next few months.

Is this kind of pattern considered acceptable to a Java developer? Is there a better way to preserve the flexibility of having number-like objects but constraints on their possible values?

like image 597
Salim Fadhley Avatar asked May 23 '26 23:05

Salim Fadhley


1 Answers

Well, first of all, no real software that deals with money uses floating-point math, because of the imprecision. See Accuracy problems section of Wikipedia page on floating-point arithmetic. A "Money" class that holds integer numbers of pennies is one common way to deal with this.

Secondly, yes, having a constructor that rejects negative numbers by throwing an exception would be a fine thing to do for such a class.

Here's a good Dr. Dobb's Journal article on the topic, with code.

like image 98
Ernest Friedman-Hill Avatar answered May 26 '26 12:05

Ernest Friedman-Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!