它是确定一个工厂方法返回null? [英] Is it OK for a factory method to return null?

查看:152
本文介绍了它是确定一个工厂方法返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解一下最佳实践在这里。它是很好的做法的工厂方法返回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?)

这篇关于它是确定一个工厂方法返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆