Is it OK for a factory method to return null?

前端 未结 4 1026
余生分开走
余生分开走 2021-02-12 03:39

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         


        
4条回答
  •  无人及你
    2021-02-12 04:09

    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 ...
    }
    

提交回复
热议问题