C
C#2y ago
DaVinki

❔ Best pattern to alleviate the pain of a many-to-many unit conversion program?

For example, converting gallons to any other volumetric unit and vice versa
4 Replies
JakenVeina
JakenVeina2y ago
assuming you don't want to just define all possible combinations and look them up from, like, a dictionary model all the "primitive" conversions that you need as edges on a graph with types being nodes and your general-purpose converter can walk the graph to find the most-efficient chain of conversions to link any two types or can identify types that can't be converted
jcotton42
jcotton422y ago
Define conversions to/from base units Eg liters for volume
Doombox
Doombox2y ago
literally solved this precise issue this way, just pick a common unit and you're gold
public enum Temperature
{
[Unit("°c", 1)]
Celsius,
[Unit("°F", typeof(FahrenheitConverter))]
Fahrenheit,
[Unit("K", typeof(KelvinConverter))]
Kelvin
}
public enum Mass
{
[Unit("g", 1)]
Grams,
[Unit("lb", 453.59237)]
Pounds,
[Unit("oz", 28.34952)]
Ounces
// etc...
}
public enum Temperature
{
[Unit("°c", 1)]
Celsius,
[Unit("°F", typeof(FahrenheitConverter))]
Fahrenheit,
[Unit("K", typeof(KelvinConverter))]
Kelvin
}
public enum Mass
{
[Unit("g", 1)]
Grams,
[Unit("lb", 453.59237)]
Pounds,
[Unit("oz", 28.34952)]
Ounces
// etc...
}
is what I ended up doing, either they use a fixed ratio or a custom converter where appropriate
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server