I’m wondering about best practice here. Is it good practice for a factory method to return null if it can’t create anything? Here’s an example:
ICommand command = CommandFactory.CreateCommand(args);
if (command != null)
command.Execute();
else
// do something else if there is no command
An alternative would be to return a NullCommand or something, I guess, but what is best practice?
I think it’s potentially reasonable for a factory method to return null in some situations, but not if it’s a method called
CreateCommand. If it wereGetCommandorFetchCommand, that might be okay… but aCreatemethod should throw an exception on failure, I would suggest.Whether you really want it to return
nullin this situation depends on the bigger picture, of course. (Is there a reasonable null object implementation you could return instead, for example?)