4 ms·
don't do this! typealias Cents = Long typealias Meters = Long Cents(3) + Meters(4) = 7L that's exactly the thing we want to prevent. the cla
by stefs 5y ago
don't do this!
typealias Cents = Long
typealias Meters = Long
Cents(3) + Meters(4) = 7L
that's exactly the thing we want to prevent.
the classes shouldn't be for units at all, the type should represent the type of unit.
so instead of a class Seconds you should have a class Duration, instead of class Meters you should have a type Distance. that's because the unit of the different types can be converted between each other.
Dollars and Cents are a bit of a bad example because currencies can't be easily converted between each other, as conversion is dependent on many factors that change over time. meters, yards, feet, lightyears, miles, chain, furlongs, whatever describe a multiple of the same thing though, so a different type for each unit isn't necessary, as the input that was used to create the instance isn' usually needed. the counter example would be datetime with timezones - a datetime with a timezone convers a lot more information than the datetime converted to UTC.