OgreVorbis
Member
So I've now encountered this problem enough times during programming and just brushed it off, but I want to increase my code quality, so I'd like to discuss this.
One of the issues with switch cases is that I often times have nearly identical code for each section, but just calling a different method. Furthermore, I have multiple different switch cases using the same case strings. Maybe in some instances it would be extreme enough that I could just somehow map strings to method names (don't know how).
Here's what I'm currently working on:
So firstly, I suppose I could create an enum, dictionary, or maybe an enum + array.
So maybe have an array like:
Now this is pretty good and kind of improves the redundancy IF I need to use the same strings in multiple switch cases (which I do). So this is cool, but is there a way to make it better?
One of the issues with switch cases is that I often times have nearly identical code for each section, but just calling a different method. Furthermore, I have multiple different switch cases using the same case strings. Maybe in some instances it would be extreme enough that I could just somehow map strings to method names (don't know how).
Here's what I'm currently working on:
C#:
private bool TimeCalc(string theParam, TimeSpan span, out string answer)
{
answer = "";
switch (theParam)
{
case "days":
answer = span.TotalDays.ToString();
break;
case "hours":
answer = span.TotalHours.ToString();
break;
case "mins":
case "minutes":
answer = span.TotalMinutes.ToString();
break;
case "secs":
case "seconds":
answer = span.TotalSeconds.ToString();
break;
case "weeks":
answer = ((span.TotalDays) / 7.0).ToString();
break;
case "months":
answer = ((span.TotalDays) / 30.437).ToString();
break;
case "years":
answer = ((span.TotalDays) / 365.0).ToString();
break;
default:
return false;
}
return true;
}
private bool FuturePastCalc(string theParam, DateTime startDate, string num, out string answer)
{
answer = "";
switch (theParam)
{
case "days":
answer = startDate.AddDays(Convert.ToDouble(num)).ToString();
break;
case "hours":
answer = startDate.AddHours(Convert.ToDouble(num)).ToString();
break;
case "mins":
case "minutes":
answer = startDate.AddMinutes(Convert.ToDouble(num)).ToString();
break;
case "secs":
case "seconds":
answer = startDate.AddSeconds(Convert.ToDouble(num)).ToString();
break;
default:
return false;
}
return true;
}
// AND MORE IN SEPARATE METHODS
So firstly, I suppose I could create an enum, dictionary, or maybe an enum + array.
So maybe have an array like:
C#:
string[] commands = new string[] {"days", "hours", "mins", ... };
enum TimeChunk
{
Days, Hours, Mins, Secs, ...
}
// Then calling would be like:
case commands[TimeChunk.Days]:
Now this is pretty good and kind of improves the redundancy IF I need to use the same strings in multiple switch cases (which I do). So this is cool, but is there a way to make it better?
Last edited: