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:
Usage:
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-
switchand a full-fledged OO approach (no real need for OO here because this specific conversion problem has a very simple domain model).