Transfers and case statements

I am looking for good reasons, if we should try to avoid switch / case statements and how to do this for listings and sentences, consider the following example: (note that this switch / register can be scattered throughout the code base)

switch (theEnum) { case MyEnum.Enum1: // dosomething case MyEnum.Enum2: // do something case MyEnum.Enum3: // do something default: throw new Exception("Unsupported enumeration: " + theEnum.ToString()); 

}

vs.

 public Dictionary<MyEnum, StrategyBase> BuildMapper() { var mapper = new Dictionary<MyEnum, StrategyBase>(); mapper[MyEnum.Enum1] = new Strategy1(); mapper[MyEnum.Enum2] = new Strategy2(); mapper[MyEnum.Enum3] = new Strategy3(); return mapper; } BuildMapper()[MyEnum.Enum1].DoSomething(); 

Option 2 is more OO, but I was wondering what others think like this approach, and if there are good and good reasons why we should strive for it or not.

It can be argued that principles such as switch / else will violate open-close, for example.

+4
source share
6 answers

For OO, you must use the visitor template

+1
source

I would make BuildMapper as static (also read-only), because it will always return the same set of words to you.

How good this is, the reason should be simple when you have a design where things are moving from one thing to another, and this mapping will always be static, obviously it is a dictionary, not if / else or switch case that hides the intention is that this is just a comparison.

+1
source

I would go to the switch if it were in one or two places. If, as you say, β€œthis switch / register can be scattered throughout the code base,” then go to the second solution.

This is not only more OO, which is good, but easier to maintain in your situation. In this case, performance and memory consumption problems are completely irrelevant, first of all, ease of maintenance and optimization (but I don’t think you will ever need to optimize this).

Also, reading loss in this case does not matter - understanding what the second approach does takes very little time.

+1
source

I think the first option is better because it looks more readable and explicit.

0
source

I would say that it comes down to what you want to achieve. It is easier to read the first sample, and it is very important if you share your code base with others. BuilderMapper may be useful if you follow some pattern.

0
source

I think you are comparing oranges and apples.

A switch is a sequential comparison between a variable and several constant data. If you don't have a 1K switch, it should be much more efficient than a dictionary.

Of course, a switch consumes much less memory than a rather complex object than a dictionary.

Finally, enumerations are not limited to declared parameters, but can be combined as β€œFlags”. This feature is not available with hashmap.

Is this satisfactory?

0
source

All Articles