它是确定一个工厂方法返回null?它是、工厂、方法、null

2023-09-03 05:41:15 作者:寒风式的伤感

我想了解一下最佳实践在这里。它是很好的做法的工厂方法返回null,如果它不能创造什么?这里有一个例子:

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

另一种方法是返回一个 NullCommand 什么的,我猜,但什么是最好的做法?

An alternative would be to return a NullCommand or something, I guess, but what is best practice?

推荐答案

我认为这是可能合理的工厂方法在某些情况下返回null,但是的没有的,如果它是一个名为方法 CreateCommand 。如果是 GetCommand FETCHCOMMAND ,这可能是正确的......但创建方法应该抛出故障异常,我会建议。

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 were GetCommand or FetchCommand, that might be okay... but a Create method should throw an exception on failure, I would suggest.

无论你的真正的希望它返回在这种情况下当然取决于大局观。 (是否有一个合理的空对象实现,你可以返回来代替,比如?)

Whether you really want it to return null in this situation depends on the bigger picture, of course. (Is there a reasonable null object implementation you could return instead, for example?)

 
精彩推荐
图片推荐