Is there a possible way to write the next switch in some shorter, readable code?
switch (SomeValue)
{
case \"001\": return DoMethod1(); break;
case \"002
In general a good alternative for switch would be using State Design Pattern other good alternative is Strategy Pattern. It will make your code more extensible and is more object oriented approach.
There must be an error with your method definitions,
class Program
{
static void Main()
{
var methods = new Dictionary<string, Func<int>>
{
{ "001", DoMethod1 }
};
}
static int DoMethod1()
{
return 1;
}
}
is perfectly valid syntax.
but, this is not better than switch
for 1 compelling and 1 subjective reason.
If you are comparing against constants or literals then you should use switch. This enables the compiler to peform compile time optimizations without additional analysis.
More subjectively, the dictionary/lookup approach is no shorter and I find it harder to read. However, it would be useful in situations where your comparison terms vary at runtime.
If you want avoid rewriting the switch
factor it into a function. Say,
Func<int> MethodsByValue(string value)
{
switch(value)
{
case "001":
return DoMethod1;
default:
return DoMethod2;
}
}
Either way,
Rather than using some arbritary strings to enumerate your methods, why not use an enum
? Then you will get additional performance and readability benefits.
I use a Mapping extension for that. This way yoy can use the following syntax:
return SomeValue
.Map("001", DoMethod1)
.Map("002", DoMethod2)
//etc
This makes it also possible to do this:
return SomeValue
.Map(1, DoMethod1)
.Map(2, DoMethod2)
.Map(x => x < 0, DoMethod3)
.Map(x => x > 5 && x < 10, DoMethod4)
.Else(4); // a simple value of a method
You can shorten what you have simply by removing the redundant break
s, and if it happens that two cases should call the same method then you can fall through:
switch (SomeValue) {
case "001": return DoMethod1();
case "002": return DoMethod2();
case "003":
case "004": return DoMethod34();
//etc..
}
As for your pseudo suggestion, and the other answer advocating it, I don't see how this is any short or more concise. However, in usage is could reduce code and be clear, such as, briefly:
Func<int> GetMethod(string key) {
return MethodsByValue[key];
}
Func<int> method = GetMethod("001");
method();