Note that there are some explanatory texts on larger screens.

plurals
  1. PODoubles with constraints in Java?
    primarykey
    data
    text
    <p>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. </p> <p>A system I'm working on deals with prices of products. All products have prices > 0.0.</p> <p>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. </p> <p>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.</p> <p>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.</p> <p>Other than that (to begin with) it will obey all the normal rules of arethmatic - it will be a subclass of Double. </p> <p>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.</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload