Search code examples
phpswitch-statementdefaultfactoryfactory-pattern

What should go into default case of a switch statement inside a Factory Method?


Factory method works great when all my object creation parameters are well-defined. However, working with legacy code, the default seems to be to 'fail silently' or write code constructs that prevent invalid data ever reaching the factory method.

What typically goes into the default: case of a switch statement inside a Factory Method?

Example below...

class Factory
{

    function getObject($param)
    {
        switch ($param)
        {
            case 'a':
                return new A();
            case 'b':
                return new B();
            default:

                //OPTION 1
                //break code execution?  Sometimes it's not desirable
                //especially in production code as introducing an
                //Exception breaks previous legacy code behavior
                throw new \RuntimeException($message, $code, $previous);

                //OPTION 2
                //fail silently? - sometimes that's the desired behavior
                //dummy object is created does nothing, and is then 
                //discarded and code execution goes on, but creating 
                //a dummy object does not seems like the right way to address the issue
                return new fakeDummyObject(); 

                //OPTION 3
                //3rd way is to construct code that never reaches 
                //default:; switch statement.  This requires
                //more work on the legacy code side
        }
    }
}

Solution

  • Throw an InvalidArgumentException. Someone’s trying to instantiate a type of object that your factory doesn’t know about.