我怎么解释,如果(XYZ == NULL)检查不是"保护" [英] how do i explain that if (xyz == null) checks are not "protective"

查看:145
本文介绍了我怎么解释,如果(XYZ == NULL)检查不是"保护"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个开发商谁不断把如果null检查

i have a few developers who constantly put If null checks

例如:

Run(Order order)
{
  if (order == null) return;
}

在他们的代码,因为他们认为,如果有人经过在他们保护他们的阶级参数为null。我想告诉他们的缺陷在他们的逻辑,因为如果有人传入null在这种情况下,最有可能的问题与消费者的代码,而是这个类的抛出异常和失败快,优雅地处理的不良行为消费者并保持隆隆的路程。

in their code as they think they are protecting their class if someone passes in a parameter that is null. I am trying to tell them the flaw in their logic because if someone is passing in null in this case, its most likely an issue with the consumer code and instead of this class throwing an exception and failing fast, it gracefully handles the bad behavior of the consumer and keep chugging away.

另一个建议是有前提条件,或未能快速抛出异常后卫类。任何事情,但忽略了一个事实,即消费者可能有一些其他的问题,我帮助掩盖它。

another suggestion is to have precondition or guard class that fail fast and throw exceptions. any thing but ignoring that fact that the consumer probably has some other issue and i am help mask it.

如何让乡亲们体会到一个事实,即类不应该' T为如此宽容。如果有人不处于良好的数据传递,他们应该被告知。

how do i get folks to appreciate the fact that your class shouldn't be so forgiving. if someone doesn't pass in good data, they should be told.

任何好的文章或建议,以帮助我得到过这个问题?

any good articles or suggestions to help me get this point across?

推荐答案

如果你的类不能接受参数,然后做的最好的事情是这样的:

If your class cannot accept null arguments, then the best thing to do is this:

if (arg == null)
    throw new ArgumentNullException();

这是远远优于得到一个 NullPointerException异常更深层次的下跌堆栈。在最坏的情况下,你会缓存的地方,并不会真正引发异常,直到很久以后,看看你有多大的快乐调试问题的然后

This is vastly preferable to getting a NullPointerException deeper down the stack. In the worst case scenario, you'll cache that null somewhere and won't actually trigger the exception until much later, and see how much fun you'll have debugging the problem then.

和如其他人所说,有时候合同说,是好的。在这种情况下,有周围的代码的某些部分保护条款是正确的 - 虽然即使这样,我会说,最好的设计是没有选择性空参数添加一个过载

And as others have stated, sometimes the contract says that null is okay. In that case, having a guard clause around some parts of the code is correct--although even then I'd say that the best design would be to add an overload without the optionally-null arguments.

这篇关于我怎么解释,如果(XYZ == NULL)检查不是"保护"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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