6

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?

asked Mar 24, 2016 at 6:49
4
  • possible duplicate of When comparing a string variable to a string literal with .equals(), is there a standard practice for the order of items? Commented Mar 24, 2016 at 7:07
  • 2
    I'd use 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. Commented Mar 24, 2016 at 10:27
  • If my intention is to accept nulls as not an error, i prefer to do it in a statement just about the variable if reasonable. In particular python's x = x if x is not None else default ... or c#'s x = x ?? default. Commented Mar 24, 2016 at 15:45
  • Sometimes you're better off failing than letting nulls through: for example, if (!"test".equals(value)) return prefix + value; Commented Apr 24, 2017 at 18:45

4 Answers 4

15

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.

answered Mar 24, 2016 at 7:06
1
  • +1 for "fail early" (a.k.a., "fail fast"). If you then go on to combine that with "be sure your tests cover these cases", then "fail early" means, "fail in testing, instead of failing at the customer site." Commented Mar 24, 2016 at 20:11
2

One goal of programming is robust code, ie. code that doesn't die horribly whenever something unexpected crops up.

in case of if ("abc".equals(myString)), the if clause doesn't get executed if the string is null, so throwing an exception isn't necessary. Of course it could be caused by bugs in code, but those should be found during developing/testing, not in production, by the customer!

Actually, i would take "abc".equals(myString) as an indication that the programmer explicitly didn't care whether the string was null or not. In critical code, i'd expect a lot more explicit checking.

answered Jul 1, 2016 at 8:30
1

If myString is nil, then one version will throw an exception, while the other will do something according to the documentation that I would have to read first. Let's assume comparing a string to nil for equality returns "false".

Possibilities: myString is never nil, then it doesn't matter. Or myString is only nil in case of some bug in the software, then an unexpected exception hopefully leading to something that gets the developer's attention is a good thing. (That's where catching exceptions and not doing anything with them is fatal). Or myString can legally be nil, and you want the comparison return false, then compare accordingly. Or myString being nil is an exceptional case that needs to get special handling, which you may not be aware of yet, then an unexpected exception will make you add the correct handling at some point.

Funny enough, in Objective-C it's exactly the other way round: Comparing to nil throws an exception, comparing nil with anything returns NO (about the same as false). So whatever you do, an Objective-C developer should do exactly the opposite!

answered Mar 24, 2016 at 8:56
0

Using "abc".equals(...) is a reasonable precaution against a condition you didn't anticipate

I actually came up with this as a solution of avoiding a NullPointerException while retaining the conciseness of the code for my company about 2 years ago. It is indeed a reasonable approach for me. The style of writing this may look a bit weird though. My team actually did laugh at this type of writing, then they realized that it is legit, and this is now established as a standard in our organization.

answered Jul 1, 2016 at 8:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.