Notes on JSR‒275 (Measures and Units)

I have been hearing misconceptions regarding JSR‒275 (weights and measures) for the JCP in the upcoming API request by JScience that provides a model for measured values which allows for unit compatibility checks and conversion. I present the following information in a question–answer form but do not claim authority other than having a personal interest:

Why does JSR‒275 use American spelling? Short answer: both work.The spelling of the units’ names—namely meter (or metre)—is a frequent complaint. JSR‒275 provides for both. I favour certain “European spellings” (albeit not the -re prefix), so I would understand that annoyance otherwise.

Does JSR‒275 provide compile-time safety? Short answer: its compile-time safety is very limited. JSR‒275 encourages—and was partly exclusively developed for—type safety. Its implementation makes type safety between units of compatible types such as meters, inches, and feet a non-issue. But it provides type safety between unit groups such as length, mass, and temperature. Generics (parametrized types) allow for very limited compile-time safety:

Unit<Length> twoKilometers = KILO(METER.add(METER));
Unit<Force> thisWillNotWork = twoKilometers;

Here, the Java compiler would complain—conversion between length and force does not make sense.
However, the following will compile:

Unit<Length> thisIsFine = Unit.valueOf("1cm");
Unit<Area> thisIsNot = thisIsFine.divide(10);

Fortunately, the compiler will generate an “unchecked cast” warning (if you are like me, you read warnings). You could also rewrite the above example to be slightly safer:

Unit<Pressure> cool = Unit.valueOf(NEWTON).times(2).asType(Pressure.class);

The above will throw a ClassCastException. A bit obnoxious though, eh?

Q. What is with some of the naming? Short answer: disambiguation.The name ‘Measurable’ for the Measurable interface reduces ambiguity. Similarly, parametrization with ‘Quantity’ reduces ambiguity but is confusing; I think ‘QuantityType’ would be better—then again, programmers hate typing.

Q. Why ‘plus’, ‘times’, ‘add’, and ‘subtract’? Short answer: Some users expect foo.add(2); to change the value of foo. The JSR‒275 developers decided that using method names like ‘plus’ makes the methods’ nature clearer. Measurable.plus(int) returns the resulting value; it does not change the value of any of the instance’s members.

Q. Can I create my own measurable classes? Short answer: yes; implement Measurable. Implementing the Measurable interface is sufficient:

public class PseudoKelvin implements Measurable<Temperature> {
    double pseudoKelvin;
}

If you are interested, I would recommend reading the proposal. Although I disagree with certain implementation aspects, I am looking forward to JSR‒275—and other Java 7 JCP JSRs. I may write on other Java 7 JCP topics.

Tags: , , , , , , , , ,

Leave a Reply