A Value Object for Durations

A value object can pair a representation with construction and arithmetic rules that preserve the meaning of a duration.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Choose a canonical scale
  2. Test arithmetic across the boundary

Choose a canonical scale

Represent 1500 milliseconds and 1.5 seconds through one internal unit when they should compare equal. Make conversion explicit at construction. Unit-aware values explain what callers need to know.

Test arithmetic across the boundary

Adding 250 milliseconds and 0.75 seconds yields one second. Clipping the values first to full seconds changes that result. Floating-point tolerances or exact integer units can support an appropriate equality and test policy.[1]

References

  1. Python Software Foundation, Python Tutorial: Classes ↩