Hi Mark,

A common approach is to encapsulate the unit and the value in a class. Eg, a money class or a weight class. These classes can then have operator overloads that allow addition, subtraction, multiplication etc. Since the class knows its unit, conversions can be done implicitly and correctly to support these operations. Martin Fowler also mentions this type of thing as a pattern here:
http://www.martinfowler.com/eaaCatalog/money.html

Cheers,
James


Mark Greenaway wrote:
Although I came to the thread a little late, I was interested to see
that an issue close to my heart came up, which is operator overloading
with respect to numeric types. The specific example of date types was
raised.

As someone who has both programmed professionally for many years and
just recently begun a science degree majoring in mathematics, I've
become interested in how to do certain calculations within programming
languages, and how those programming languages could be improved to make
writing numeric code less error prone.

At the moment, I spend some of my time calculating unit conversions:
degrees to radians, electrovolts to joules, angstroms to metres,
concentration of H+ to ph etc. etc. It's fun the first time, a little
less so the second time and downright tedious from then on. I'm sure
similiar problems come up in other fields over and over again. For
instance, some people working in financial institutions define a
currency type that includes not only a quantity but also the currency,
be it francs, dollars, pounds or whatever.

I was wondering if anyone was aware of a standard approach
developing numeric types that include their units, or other information
relevant to them. For instance, if you had a weight in grams and another
weight in kilograms, and you attempted to do arithmetic on them, it
would make the appropriate unit conversions for you. If you were
attempting to do a calculation that makes no sense, such as adding
weight to time, it could signal an error (preferably at compile time).
Of course, multiplying and dividing by different types of units is fine.
This sort of unit checking could catch a whole class of errors that are
often made in routine calculations.

I'm sure I'm not the first person to have thought of this. Has anyone
seen or used data types that use these sorts of ideas?

Mark
_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders

_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders

Reply via email to