4. Defining a Numeric Type Having an Additive Unit of Measure

4.1. Unit of measure in modeling real-world data

4.1.1. Not like pure number classes

The examples we looked at in Chapter 3, such as Fraction and Complex (despite its name), are simple because they’re closed under all four arithmetic operations. Whenever x and y are Complex objects, then x+y, x-y, x*y, and x/y are also Complex objects (except for division by zero). We didn’t have to think about which arithmetic operators to implement and what their results should be.

Most numeric data in the real world, however, have some unit of measure. An amount of money may be measured in dollars, a distance in meters, and a temperature in degrees Kelvin. Such data are rarely closed under all ...

Get Object-Oriented Computation in C++ and Java: A Practical Guide to Design Patterns for Object-Oriented Computing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.