检查null - 什么顺序? [英] Checking for null - what order?

查看:94
本文介绍了检查null - 什么顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查空值时,我使用:

String str;

if(str == null){
    //...
}

但我也见过这个:

if(null == str){
    //...
}

使用一个是否有任何优势在另一个?或者只是为了提高可读性?

Is there any advantage of using one over the other? Or is it just to improve readability?

推荐答案

第二个版本( null == str )被称为 yoda条件

The second version ( null == str ) is called a yoda condition.

它们都会导致相同的行为,但第二个有一个优点:它当您忘记一个 = 时,可以防止您意外更改变量。在这种情况下,编译器会在该行返回错误,并且您不会留下代码的奇怪行为以及由此产生的调试。

They both result in the same behavior, but the second one has one advantage: It prevents you from accidentally changing a variable, when you forget one =. In that case the compiler returns an error at that row and you're not left with some weird behavior of your code and the resulting debugging.

这篇关于检查null - 什么顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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