从 xbox360 XNA api 方法返回 null。不好的做法?
我一直认为对于要响应的方法调用来说,返回 null 对象是一种不好的做法。 ,我假设
Int GetFieldByID( String IDString );
现在
Int m_MyReturnedID = GetFieldByID( "myGamerTag" );
如果找不到 ID,我们可能会返回 -1,然后处理它,而不是返回 null 对象,因为这实际上可能意味着内部出了问题。不管怎样,我刚刚在 XNA 开发者网站上看到了这个:
你可以 看:
返回值
网络玩家匹配 请求的 ID,如果没有则为 null 已找到匹配的玩家。
我的先入之见是否错误,即返回这样的空对象是不好的做法?我突然产生了怀疑,因为我认为 M$ 开发人员绝对应该知道他们在为 XNA/Live 等服务做什么,尤其是在各种迭代之后。
谢谢
I always considered returning a null object to be bad practice for a method call that is to be responded to. Lets say
Int GetFieldByID( String IDString );
so
Int m_MyReturnedID = GetFieldByID( "myGamerTag" );
Now, I'd assume that if the ID could not be found, we might return -1 and then handle that instead of returning a null object since that might in fact mean something went wrong internally. Anyway, I was just over on the XNA developer website and was looking at this:
As you can see:
Return Value
Network gamer matching
the requested ID, or null if no
matching gamer was found.
Am I wrong in my preconception that returning a null object like this is bad practice? I suddenly have my doubts because I would assume that M$ developers should definitely know what they are doing for a service like XNA/Live etc, especially after various iterations.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在这里描述了两种不同的情况:
Nullable 类型也是如此。
值类型不能为 null,这就是为什么您可能会在“未找到”情况下返回
-1
。您通常无法返回0
,因为大多数情况下零是有效值。在本例中,-1
是一个哨兵值。现在,引用引用类型(
class
)对象的变量可以为空(即:不引用任何目的)。但是,您也可以创建引用类型,使其具有表示“无效”的“哨兵状态”。这当然是一件非常痛苦的事情。不要这样做。
不要检查这个:
你会这样做:
这是更多的工作,即使某些东西强制非空,你仍然必须这样做:
哪个不'并没有真正为你赢得任何东西。 另外,您必须编写所有额外的代码来处理您编写的每个类中的额外状态位。
你的理论的实际问题是你的想法是,如果“内部出现问题”,方法应该返回
null
。在这种情况下,该方法几乎肯定会抛出异常。There are two different situations you're describing here:
Nullable
types too.A value type cannot be null, which is why you might return
-1
for a "not found" situation. You often cannot return0
because most of the time zero is a valid value. In this case-1
is a sentinel value.Now a variable that refers to a reference type (
class
) object can be null (ie: not referencing any object). However you could also create your reference type such that it has a "sentinel state" that represents "not valid".This is, of course, a complete pain in the ass. Don't do it.
Instead of checking this:
You'd be doing this:
Which is more work, and even if something enforced non-null-ness, you'd still have to do this:
Which doesn't really win you anything. Plus you'd have to write all the extra code to handle the extra bit of state in every single class that you write.
The actual problem with your theory is your idea that a method should return
null
if "something went wrong internally". In that case the method should almost certianly throw an exception.