5 ms·
I prefer to have a single class which stores an SI unit, as in final class Temperature { private final double kelvin; public static Temperature from
by dlubarov 13y ago
I prefer to have a single class which stores an SI unit, as in
final class Temperature {
private final double kelvin;
public static Temperature fromKelvin() { ... }
public static Temperature fromCelcius() { ... }
public static Temperature fromFahrenheit() { ... }
public double getKelvin() { ... }
public double getCelcius() { ... }
public double getFahrenheit() { ... }
}
This avoids the quadratic explosion of conversion methods.
A more complete example - https://github.com/dlubarov/daniel/blob/master/data/src/daniel/data/unit/Duration.java https://github.com/dlubarov/daniel/blob/master/data/src/dani...
- Retric 13y agoOne way to do this is to have a super class for each measurement type with a canonical measurement. So Temperature,Mass,Time,Distance etc it's slower but this way you can always get any measurement to come out without doing kg>lb, grams>lb, ounces>LB because it ends up as kg>kg>lb, grams>kg>lb etc.
- hrjet 13y agoBut this solution doesn't solve the original problem described in the article. With your API, it is easy for a programmer to use a temperature in Celcius as a temperature in Kelvins and the type system can't catch it.
- dlubarov 13y agoWell, most code can just pass around Temperature objects without dealing with any particular units. There's no opportunity to mix up units there. When some code needs to actually get a number out, say for the purpose of logging, it's possible to screw up with either approach. With the author's classes, you could do void printTemperature(DegCelsius temperature) { log("Temperature in Kelvin: %f", temperature.getDegrees()); } With this Temperate class, you could do void printTemperature(Temperature temperature) { log("Temperature in Kelvin: %f", temperature.getCelcius()); } As the author says, "wrong code should look wrong." I think both of these look pretty wrong.
- hrjet 13y agoWith the author's code you can define a print() function inside each temperature class, so that there is no mixup of units during printing. Or let the class supply its suffix instead of hardcoding it in an external print() function. It might not be always possible to follow that technique, but in general, it is better (according to the article, and I agree) to retain as much information at compile time as possible.