4 ms·
You should define separate types for “cents” and “dollars”. And, probably operations to convert between the types.
by metafunctor 4y ago
You should define separate types for “cents” and “dollars”. And, probably operations to convert between the types.
- dragonwriter 4y agoYou can have a single type for “money” (or maybe just “us_money”) with separate cents/dollars/mills factories and accessors, and no access to a numeric value except through the accessors. You can do similar things with other dimensions like “length”. Or you can go whole hog, and have a single “type” for unit-aware values from which you can only successfully extract a unitless number by specifying a unit which is dimensionally compatible. But most projects won’t do any of these because they will start out thinking they don’t need it, and by the time they realize the value they’ll think the cost of converting existing code is too high.
- diarrhea 4y agoIn physics, dimensionality makes sense. How would one handle money? Can it be represented the same way? A new dimension, next to length, time etc? It would allow to express money per time, eg dollars per second, for example.
- dragonwriter 4y ago> How would one handle money? Can it be represented the same way? Any particular currency can be modelled simply as a single dimension; “money” more generally is more complex. You can either use a single currency of account, track exchange rates for other currencies with it over time, and convert other currencies into it based on the time applicable to the event, or you can track each currency as a separate domain and convert based on the applicable exchange rate for a particular purpose ad hoc based on the specific situation. (There’s probably other approaches that work, but those seem to be, in outline, the most obvious.)
- metafunctor 4y agoYes, good point. This in fact what I've done previously in an application that was dealing with monetary values. They were basically fixnums with a unit piggybacked on, plus some money-specific operations. The money type should be compatible with generic interfaces so existing sorting and aggregation functions, for example, can directly on them.