Strongly typed quantities in Java

An interesting project at

From their description:

 Let's take the following example:

        class Person {
            void setWeight(double weight);

Should the weight be in pound, kilogram ??
With quantities there is no room for error:

        class Person {
            void setWeight(Quantity<Mass> weight);

Not only the interface is cleaner (the weight has to be of mass type); 
but also there is no confusion on the measurement unit:

        double weightInKg = weight.doubleValue(SI.KILOGRAM);
        double weightInLb = weight.doubleValue(NonSI.POUND);

Quantities work hand-in-hand with units (also parameterized). 
For example, the following would result in compile-time error:

        double weightInGal = weight.doubleValue(NonSI.GALLON); // Compile error, Unit<Mass> required.

Edit: fixed lt, gt signs

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

yikes, code between less than and greater than sign lost!

I don't know how to keep Java generics representation (which uses less than, greater than...I guess html thinks its an html tag). Perhaps and editor can help!

Basic HTML

Use &lt; and &gt; in place of < and >. You can also use &amp; in place of &- so to type in &lt; in this message, I actually had to type &amp;lt; (and so on). Also, previewing the post helps catch things like this (it caught bugs in this post).

Object-oriented units of measurement

Eric Allen, David Chase, Victor Luchangco, Jan-Willem Maessen and Guy L. Steele, Jr. had a very interesting paper on this subject at OOPSLA 2004: Object-oriented units of measurement. You also might want to check out their followup paper at FOOL 2005, A Core Calculus of Metaclasses.

Also, at OOPSLA 2005 there was a practitioner report on implementing support for units of measurement in Smalltalk: Arithmetic with Measurements on Dynamically Typed Object Oriented Languages

See also these previous LtU topics: Is "type" a fundamental intrinsic property of values?, Hungarian Notation vs The Right Thing


(the weight has to be of mass type);

This is a very ironic statement about something targeted at getting the units straight. Weight is mass x gravity. The method should be named setMass() instead.

Also, the problem with computations with units is that doubleValue() method itself. Their example:

Measure v = new Measure(20, 0.1, LITER);

would be more like

Measure v = new Measure( quantityInYards.doubleValue()**3, 0.1, LITER);

. The fundamental thing about values with units is that they can't be separated while performing the operations. As soon as you have a method that splits them, you open the floodgates again.


And Java does nothing to help you get this right, thanks to the language designers' decision to allow themselves to use operator overloading, but not any language user.