比较常量等于对象或对象等于常量

时间:2017-07-20 10:14:51

标签: java coding-style

关注Java best-java-coding-practices.htm,他们说我们需要对已知字符串常量调用.equals而不是 UNKNOWN变量

String string = new Test().getString();
// always compare like this, this will never throw NPE
System.out.println("CONSTANT.equals(string):"+CONSTANT.equals(string));
System.out.println("Comparision like string.equals(CONSTANT) may throw NullPointerException");
// next statement will throw NPE
System.out.println("string.equals(CONSTANT):"+string.equals(CONSTANT));

那么 KNOWN变量怎么样?我们还应该用这种方式吗?

例如,如果我从服务器和服务器收到一个对象,则通知该对象从不为空。
如果我想将此对象与常量

进行比较
// CONS: it may return NPE if server return null (for example server do wrong) => app crash
// PRO: when we read this code, we have a mindset that object never null, if it null it is the server bug
object.equals(CONSTANT)

// CONS: When we read this code, we never know why and when object == null so it confusing. 
// It not return NPE so code still running and we may have some problem with UI or logic
// PRO: it never return NPE
CONSTANT.equals(object)

我们非常感谢任何建议。对我来说,我更喜欢object.equals(CONSTANT)已知变量但我的团队没有。

更新我认为

CONSTANT.equals(object)

类似

try{
   object.equals(CONSTANT)
catch(NullPointerException ex){
   // don't handle or explain anything
}

0 个答案:

没有答案
相关问题