I want to return an Interface and inside a switch statement I would like to set it. Is this a bad design?
private IResultEntity GetEntity(char? someType)
{
IResultEntity entity = null;
switch (someType)
{
case 'L': //life
entity = new LifeEntity();
break;
case 'P': //property
entity = new PropertyEntity();
break;
case 'D': //disability
entity = new DisabilityEntity();
break;
case 'C': //credit card
entity = new CreditCardEntity();
break;
}
return entity;
}
Object Oriented Language has very powerful feature of Polymorphism, it is used to remove if/else or switch case in code. Code without condition is easy to read. There are some places where you have to put them and one of such example is Factory/ServiceProvider class.
Switch statements are often (and rightfully, in my opinion) considered to be a code smell. A code smell, if you'll recall, is a superficial characteristic of code that is often indicative of deeper problems. It's similar in concept to the term “red flag” for interpersonal relationships.
The switch statement is used to test the equality of a variable against several values specified in the test cases. Java is one of the most widely used programming languages used today.
In C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
I don't usually mind switch statements in a factory, provided I can group and control all of the derived classes that I want my factory to create in advance.
Sometimes,maybe a user-created plugin might want to add it's own classes to that switch list, and then a swich statement is not enough.
I found this good source for some more info on creating some more powerfull/versatile factory classes
A good middle-ground approach I usually take is to keep a static Dictionary< string,Type > for each factory class.
People can just "register" their own implementations using some sort of
Factories.TypeRegistration.StaticDictionary.Add("somekey",typeof(MyDerivedClass))
(or better yet, use a Registration method and hide the StaticDictionary)
then the Factory has an easy task of creating an instance by performing a lookup in the table:
Activator.CreateInstance(Factories.TypeRegistration.StaticDictionary["somekey"]);
I dont know, which possibilities you have in c#, but it is still better to have one switch in a factory method than having switches all over the place. In a factory method, a switch is tolerable -- but better have it well documented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With