3 ms·
If the function breaks down outside of a certain range, I would have the function return an "out-of-range" failure. Force the caller to handle this case and use
by cbeach 2y ago
If the function breaks down outside of a certain range, I would have the function return an "out-of-range" failure. Force the caller to handle this case and use the type name as documentation. Example Scala 3 code:
enum TemperatureError:
case BelowAbsoluteZero(actual: Double)
def celsiusToFahrenheit(celsius: Double): Either[TemperatureError, Double] =
if celsius < -273.15 then
Left(TemperatureError.BelowAbsoluteZero(celsius))
else
Right(celsius * 9.0 / 5.0 + 32.0)
- rhelz 2y agoI love this way of handling errors. Very nice. Yet still, the code is a description of what the code does, not what it should do. For example, I'm sure Scala has very well defined behavior when the input is, say, a NAN. So we know what the code does do in this case. Does that tell us what it should do?
- cbeach 2y agoIn Scala there's no such thing as NaN because Scala has a strong type system (one of the most powerful type systems available in any language). That said, since it's a JVM language, Scala does unfortunately still support nulls. Scala developers don't ever use null for anything (other than interop with legacy Java libraries) but still, the threat is there. I'm interested in your comments about intent. What improvements would you implement in the example code I gave?
- rhelz 2y agoNAN is a part of the IEEE standard for floating point operations. AFAIK there's nothing which would prevent a NaN from being passed into your function--because NaN is a possible value for a double. I believe what would happen in that case is that the comparison with (celsius < -273.15) would return false, and so it would not return an error object, but it would fall through into multiplying the Nan by 9, dividing by 5, and then adding 32. All of these results would return a NaN, due to Nan propagation, and then the function would return a NaN. I don't know Scala at all, so please let me know if any of this is wrong. --//-- As for what changes to make: well, I'd add a comment which said that this function should take a temperature measured in Celsius and return the same temperature measured in Fahrenheit. No matter how much time you spend designing a function (and, ipso facto, how much money your employer spends for you to design that function) you are never going to foresee all possible ways that function will be used. But that's ok--somebody can come along and fix a bug, or enhance it, if they know what the function should be doing. This just can't be the code itself saying what it should be doing. If the code itself documents what the function should be doing, then it can't have a bug--what is is doing is exactly identical to what it should be doing.