Search code examples
c#.netfactory-pattern

C# factory default return


I have created a simple factory and before I extend it to cover other implementations I was wondering what would be the correct/recommended behavior for returning from a switch/default.

In the below case I am using an enumeration(SerialisationTypes) to determine the required concrete implementation and by default I am planning to return a JSON serialiser implementation through the parameter less method but would this be correct behavior on the Default of the switch statement or should I throw an exception?

namespace Helper.Core.Serialisation
{
    internal class SerialisationFactory
    {
        internal ISerialiser Create()
        {
            return Create(SerialisationTypes.JsonSerialiser);
        }

        internal ISerialiser Create(SerialisationTypes type)
        {
            switch (type)
            {
                case SerialisationTypes.JsonSerialiser:
                    return new JSonSerialiser();
                default:
                    return new JSonSerialiser();
            }
        }
    }
}

Solution

  • You'd be better off throwing an exception, as the user is requesting something that you don't implement.

    Plus, in your code, if the enumeration has additional values (eg XmlSerialiser, ProtbufSerializer etc) then you'll always be returning a JSonSerialiser, which will lead to hard to find bugs. It's better to throw an exception and then fix the code.