Java:“ xx” .equals(variable)比variable.equals(“ xx”)更好,是吗? [英] Java : "xx".equals(variable) better than variable.equals("xx") , TRUE?

查看:83
本文介绍了Java:“ xx” .equals(variable)比variable.equals(“ xx”)更好,是吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看我认为值得怀疑的Java最佳实践和推荐编码手册。

I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.

建议:

String variable;

"xx".equals(variable) // OK

variable.equals("xx") //Not recomended

因为防止出现不受控制的NullPointerException

Because prevents appearance of NullPointerException that are not controlled

这是真的吗?

推荐答案

这是一种非常常见的技术,如果变量为null,则导致测试返回false,而不是抛出 NullPointerException 。但是我想我会有所不同,说我不会认为这是您应该始终遵循的建议。

This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.


  • 我绝对认为这是所有Java程序员都应该意识到的东西,因为它是一个常见的习惯用法。

  • 这也是使代码更简洁的一种有用技术(您可以处理null和not null的情况

但是:


  • 这使您的代码更难阅读:如果蓝色是天空。 ..

  • 如果您刚刚检查了上一行的参数不为null,则没有必要。

  • 如果您忘记测试是否为空,并且有人确实带有一个空参数,而您并不期望它为空,那么 NullPointerException 不一定是最糟糕的结果。假装一切正常,直到以后最终失败为止,这并不是一个更好的选择。快速失败是个好习惯。

  • It makes your code harder to read: "If blue is the sky..."
  • If you have just checked that your argument is not null on the previous line then it is unnecessary.
  • If you forgot to test for null and someone does come with a null argument that you weren't expecting it then a NullPointerException is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.

我个人认为 都不应该使用此技术案件。我认为应该留给程序员逐案判断。重要的是要确保您以适当的方式处理了空值,并且如何处理取决于情况。检查空值的正确处理可能是测试/代码审查指南的一部分。

Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.

这篇关于Java:“ xx” .equals(variable)比variable.equals(“ xx”)更好,是吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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