I'm writing something that handles length units, say, metres and feet. I don't want to accidentally convert between them (trying to avoid something like the Mars Climate Orbiter crash).

I'd like to use the type system for this, so that the compiler will catch these kind of errors, and only be able to convert between these types very explicitly.

I'm writing this in Java, which I'm not super familiar with. Looks like I can't subclass Double.

How should I go about this? I guess I could define my own classes Metres and Feet but I'd lose the benefits of automatic unboxing. If this was C++ I could add an operator double and add arithmetic overloads to make sure I can't operate mixed types, but it looks like I can't do this in Java?

  • 3
    Why do you want to distinguish between these two units? It seems to me that they both describe the same thing. Therefore, you should most likely have a single class Distance which doesn't inherit from another class and has the static methods fromMeters and fromFeet. Then, you can implement the method add(Distance otherDistance) and handle the operation internally. – Vincent Savard Jul 5 '18 at 17:32
  • 8
    Java does not meet your stated needs: it lacks operator overloading, so your math expressions will be inelegant, it lacks (for now, see infoq.com/news/2018/06/JavaValuesJun18) user-defined value types, so you will be stuck with the performance impact of boxing. Are you wedded to Java? If you wish to stay in the JVM family of languages, Scala has a units-of-measure package. If you want to get out of the JVM world and into the .NET world, F# also has units of measure. A functional language might be a better fit for your problem; what is the business domain of the program? – Eric Lippert Jul 5 '18 at 18:11
  • 1
    This Joel on Software post suggests a naming convention to plug the type hole in a similar circumstance, FWIW – user214290 Jul 5 '18 at 19:25
  • 2
    @Martin "A unit means nothing to a type system": Yes it does when it's part of the type system, as in Scala or F#. It forbids adding apples and oranges at compile time (and also enables more advanced kinds of checks). See also e.g. pdfs.semanticscholar.org/ed8a/… – Marc Sigrist Jul 6 '18 at 5:32
  • 1
    @GregBurghardt The result will be 4,548e+10 ångström, obviously. – Joker_vD Jul 6 '18 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.