just wondering which approach would be better if both blocks of code would yield the same result:
string from = ddFrom.SelectedItem.ToString(),
to = ddTo.SelectedItem.ToString();
switch(from)
{
case "celsius":
switch(to)
{
case "celsius":
break;
case "fahrenheit":
break;
case "kelvin":
break;
}
break;
case "fahrenheit":
switch(to)
{
case "celsius":
break;
case "fahrenheit":
break;
case "kelvin":
break;
}
break;
case "kelvin":
switch(to)
{
case "celsius":
break;
case "fahrenheit":
break;
case "kelvin":
break;
}
break;
}
or this one:
string from = ddFrom.SelectedItem.ToString(),
to = ddTo.SelectedItem.ToString(),
conversion = from + to;
switch(conversion)
{
case "celsiusfahrenheit":
break;
case "celsiuskelvin":
break;
case "fahrenheitcelsius":
break;
case "fahrenheitkelvin":
break;
case "kelvincelsius":
break;
case "kelvinfahrenheit":
break;
}
Thanks.
Second option is preferable because, as everyone has said, it makes the code look and feel better.
However, you might want to consider a more architected option:
public class TemperatureConverter
{
private static readonly IDictionary<Tuple<string, string>, Func<double, double>> ConverterMap =
new Dictionary<Tuple<string, string>, Func<double, double>>
{
{ Tuple.Create("celsius", "kelvin"), t => t + 273 },
// add similar lines to convert from/to other measurements
}
public static double Convert(double degrees, string fromType, string toType)
{
fromType = fromType.ToLowerInvariant();
toType = toType.ToLowerInvariant();
if (fromType == toType) {
return degrees; // no conversion necessary
}
return ConverterMap[Tuple.Create(fromType, toType)](degrees);
}
}
Usage:
TemperatureConverter.Convert(0, "celcius", "kelvin");
Of course this can be further improved (using enumeration values instead of strings for the temperature types comes to mind first, also some error checking is in order), but the general idea is there.
IMHO this is a good middle ground approach between the old school C-style mega-switch
and a full-fledged OO approach (no real need for OO here because this specific conversion problem has a very simple domain model).
The, second one would be better for fast result and less coding as it is giving the Same result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With