In certain types of code (e.g. simulation/ games/ optimization), many physical quantities/properties are stored, manipulated, and exposed for objects (position, velocity, distance, area, volume, time, time-differences). In these types of code, all these quantities are typically represented by floating point numbers, i.e. doubles in c#.
This allows you to add times to distances, area’s to volumes, times to times, and positions to positions.
But you never want to do this. You will only want to add time-differences to times, distances to other distances or positions, and multiply areas with distances. Still, errors are easily made, especially when working on code by someone else.
There are many options to mitigate this danger. You could define custom classes representing various physical quantities, and subsequently forbidding certain types of interactions programmatically. Or you adhere to strict naming conventions (e.g. delay_timedifference). Which of those two options is best under what (if any) circumstances? How to implement the first option? How to do the naming for the second option?
Often, the second option is used, but more for convenience. Naming becomes a matter of making it obvious what you’re dealing with, ie: naming properties
AreaandVolume, but even then, there is a unit issue.You can handle the first case by making an entire set of custom classes (or immutable struct types) to handle each of the different combinations, which can work well, but can make the code quite a bit more cumbersome to work with. The
DateTimestruct in the framework is a good example – at its core, it’s basically just a long integer value, but it’s wrapped into a struct to prevent its usage as anything but a moment in time.Note that other languages have options for this – for example, F# allows Units to be handled at a language level, but this isn’t supported in any way in C#.