javaunits-of-measurement

Storing and Managing unit of measurements


I am dealing with a clinical application that uses both base and derived units of measure.

Currently, we store them as a text field in a separate column in each table that requires units. However, I am planning to redesign the database so that we have all the units of measurement in one table and use foreign keys in the table that require UOMs.

This kind of solves the problem at the database level. However, in the Java code, we use String to store the units like so:

class Foo {
    double amount;
    String unit;
}

I imagine using String to store units could become a nightmare going forward. I need suggestions on a clean way to manage units of measure so that I can, say, compare two Foos or add two Foos by making sure they have the same units, etc.


Solution

  • I think you should have a better abstraction than a String; it's little more than a primitive.

    I'd write a Units class that would parse and store those Strings from the database and allow you to compare them easily.

    public class Units {
        private final String name;
    
        // constructors, equals, hashCode, toString and other operations here
    }
    

    It might also be useful to have categories of Units. (You can measure pressure a lot of ways.) British and international units can describe the same thing.

    You might also have categories based on physical quantities (e.g. force, mass, charge, time, etc.)