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 comma
Returning null
in this case will make your method harder to use; clients have to be aware of an implicit failure condition. Instead, throw an exception, and you can also provide a separate method for clients to test for this condition:
if (CommandFactory.CanCreate(args)) {
ICommand command = CommandFactory.Create(args);
command.Execute();
}
Or make the factory instantiatable; which would be better if you need to pre-process args
:
CommandFactory factory = new CommandFactory(args);
if (factory.IsValid()) {
ICommand command = factory.Create();
command.Execute();
}
The interface of the factory now makes it clear and explicit that creation might fail, but it still requires the client to use the checking method. Another option is this:
ICommand command;
if (CommandFactory.TryCreate(args, out command)) {
// creation succeeded ...
}