Tag Archives: duration

How to use Unit Types for Safe and Readable Code

In your program code, you often have to deal with values which have a given unit. The problem is, this unit is often completely lost. If you do not add the unit as a comment or as part of the variable name, there is the risk you accidentally make wrong conversions.

This article describes how you declare new types to handle the units for common time values. It also explains how to use user defined literals so you can write values like 100_ms in your code.

The shown example code will only work with 32-bit processors, like the SAM D21 used in the Arduino Zero or Adafruit Feather M0 platform. It is possible to adapt the code to compile on the AVR toolchain for Arduino Uno and similar, but this is not part of this article.

Another requirement is your C++ compiler has to support the language standard C++11. This standard is eight years old and should meanwhile be supported by all compilers.

What is the Issue not Using Units?

Imagine an interface where you set the delay of some action:

void setActionDelay(uint32_t delay);

The problem with this interface is the lack of unit information. Do you pass seconds, milliseconds, nanoseconds or any other unit to this function? If you do not document the function, the user has to guess or study the implementation of the function.

/// Set the Delay for the action.
/// @param delay The delay in milliseconds.
void setActionDelay(uint32_t delay);

Much better. Now the interface user can read the API documentation and is aware you expect milliseconds. They will start using the code like this:

void setup() {
  // ...
  // ...

Again, the unit is lost. If someone else is reading this code, they have to look up the API documentation to find out about the millisecond unit and to know, 1000 means 1000 milliseconds.

Decorate Names is Ugly

A standard solution is to decorate function and variable names. The resulting interface looks like this:

Continue reading How to use Unit Types for Safe and Readable Code