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.
source share