I was talking with my CompSci professor and he suggested that all String .equals
methods be written as:
"Hello World".equals(fooString);
rather than:
fooString.equals("Hello World");
Both of these lines compile, but I was wondering what are the benefits of the first way? I've always done it the latter way. Is this wrong? What is common/conventional?
The first way guarantees NullPointerException
is never thrown, while the second one may risk getting NullPointerException
if the fooString
happens to be null
.
However, in the end, it all boils down to the requirement. If the requirement specifies that the null
case should not happen at all, or should be treated differently, then writing in the 2nd way (fooString.equals()
) helps you detect the implementation flaw. If you can treat null
as just another case, then the 1st way is fine.
The first way ensures that you will not receive a NullPointerException when you perform the comparison. This Exception is thrown (occurs) when you try to invoke a method on an object that doesn't exist.
Somewhat Relevant Tangent Below: Peruse At Own Risk
As a note, though, I have very, very rarely actually seen this technique or coding style used in a legitimate production environment. There are two reasons for this.
First, programs you write will almost always want to do something special or different in the case that your variable contains null. This is because it usually indicates an error in some other part of the code's function or a special case that needs to be addressed. As such, null checking should always occur before any comparisons or method calls on the object (in this case, your String fooString
).
Second, fooString.equals("Hello World")
just tends to make your code slightly more readable. The logical significance of the first technique in your code takes a few seconds to process correctly, and it is easy to make an error of judgment when you are skimming over hundreds or thousands of lines of code. This is actually much less trivial than it sounds, because in the working world, more often than not, there are very large and very old programs that will be patched by people who knew nothing about them before glancing at them to solve the problem. Code readability contributes in a huge way to a company's ability to perform fast triage and solve long term problems.
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