Consider this line:
if (object.getAttribute("someAttr").equals("true")) { // ....
Obviously this line is a potential bug, the attribute might be null
and we will get a NullPointerException
. So we need to refactor it to one of two choices:
First option:
if ("true".equals(object.getAttribute("someAttr"))) { // ....
Second option:
String attr = object.getAttribute("someAttr"); if (attr != null) { if (attr.equals("true")) { // ....
The first option is awkward to read but more concise, while the second one is clear in intent, but verbose.
Which option do you prefer in terms of readability?
Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.
How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.
It is generally a bad practice to catch NullPointerException.
Avoiding Null Checks Through Coding Practices It's usually a good practice to write code that fails early. So, if an API accepts multiple parameters that aren't allowed to be null, it's better to check for every non-null parameter as a precondition of the API.
I've always used
if ("true".equals(object.getAttribute("someAttr"))) { // ....
because although it is a little more difficult to read it's much less verbose and I think it's readable enough so you get used to it very easily
In the second option, you can take advantage of short-circuiting &&
:
String attr = object.getAttribute("someAttr"); if (attr != null && attr.equals("true")) { // ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With