Java – Is “use “abc”.equals(theString) instead of theString.equals(“abc”) to avoid null pointer exception” already problematic in terms of business logic

javanullstring-matchingstrings

I heard numerous times that when comparing Strings in Java, to avoid null pointer exception, we should use "abc".equals(myString) instead of myString.equals("abc"), but my question is, is this idea already problematic in terms of business logic?

Suppose myString should not be empty in normal conditions, if we just use "abc".equals(myString) to avoid null pointer exception, we may miss some bugs that is related to the root cause of null Strings (e.g.: a form with incomplete field or a database missing corresponding column), so we should let null pointer exceptions throws naturally, or always check null separately first:

if(myString==null){
}else if(myString.equals("abc")){
}

to ensure we can find bugs or at least having routes to handle abnormal conditions that cause null input, is that true? And even null is assumed as valid, should I still need to write something like:

if(myString==null || myString.equals("")){
}

to emphasise or remind other developers that now I assume null is normal?

Best Answer

Using "abc".equals(...) is a reasonable precaution against a condition you didn't anticipate, but doesn't really solve any problems. Maybe this particular method doesn't care that myString is null (the string comparison returns false, but that's it), but what about elsewhere? Now there's this null value working its way through your logic that's not supposed to be there.

In this particular case, it might not matter, but in another, letting this invalid value pass through part of the logic could lead to an incorrect state later on (e.g. an address with the city missing). Fail early!

If myString should not be null, then write the code so that it can't be. Add contracts to your methods, or at least some in-method argument validation to ensure invalid values are dealt with before the method's logic ever executes. Then be sure your tests cover these cases.