Gracefully avoiding NullPointerException in Java

前端 未结 9 1408
夕颜
夕颜 2020-11-30 04:02

Consider this line:

if (object.getAttribute(\"someAttr\").equals(\"true\")) { // ....

Obviously this line is a potential bug, the attribute

9条回答
  •  猫巷女王i
    2020-11-30 04:47

    There are certain situations where the concise approach feels wrong to start with but effectively becomes idiomatic. This is one of them; the other is something like:

    String line;
    while ((line = bufferedReader.readLine()) != null) {
      // Use line
    }
    

    Side effects in a condition? Unthinkable! Except it's basically nicer than the alternatives, when you recognise the particular pattern.

    This pattern is similar - it's so common in Java that I'd expect any reasonably experienced developer to recognise it. The result is pleasantly concise. (Amusingly, I sometimes see C# code which uses the same idiom, unnecessarily - the equality operator works fine with strings in C#.)

    Bottom line: use the first version, and become familiar with it.

提交回复
热议问题