When implementing a factory or simple factory, what would go against using a Type instead of an Enum to specify the class to instantiate?
For example
public class SimpleFactory
{
public static ITest Create(Type type)
{
if (type == typeof(ConcreteTest1))
return new ConcreteTest1();
if (type == typeof(ConcreteTest2))
return new ConcreteTest2();
throw new Exception("Invalid type");
}
}
Using an enum is more restrictive, which means that it is less likely that the user will try to use your factory with an unsupported type.
I find that it's good to do everything possible when defining an API to discourage usage patterns that will cause exceptions to be thrown. Allowing "Type" in this case opens up millions of ways to call your function that will result in:
throw new Exception("Invalid type");
Using an enum would eliminate this. The only way an enum would throw would be if the user did something noticably wrong.
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