Should we consider `value` of `Measurement` dangerous?

The lovely Measurement type has a property value.

My team spotted a bug in our use of Measurement yesterday. We were talking to an API wanting to give it a measurement in meters. Our code looked like this: otherAPI(meters: measurement.value). This call is of course wrong, because measurement may not be a measurement in meters. The current unit is part of its value, not its type.

We've added test coverage to hopefully avoid this bug in future! However, it occurs to me that this entire class of possible bug could be eliminated by deprecating the value property and changing it for a function value(in unit: UnitType). Eg: otherAPI(meters: distance.value(in: .meters)). While one can still make a mistake here, it is a great deal less likely, and any error is pretty clear in the code.

I would like to pitch this suggestion for an API change, but I wonder if I'm missing something here and there's a really good reason for the value API existing?

1 Like

I'd treat value as "rawValue", e.g. when creating Measurement(value: 200, unit: UnitLength.centimeters) and calling value on it I'd expect to get 200 back without any possible conversion involved.

As a side note

if you add centimetres to centimetres the unit (and thus the value) of the result is centimetres, whilst if you add centimetres to millimetres the unit (and thus the value) of the result is in meters (not in the units of one of the operands as one'd expect).

There's built-in converted(to: .meters).value which I guess would be equivalent to your value(in: .meters).

1 Like