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?
Object.equals(a, b)
for comparisons. Add an explicit!= null
assertion if you need that instead of abusing a method call to check it implicitly.if (!"test".equals(value)) return prefix + value;