Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to use a .equals method in Java?

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?

like image 750
Nosrettap Avatar asked Sep 19 '12 00:09

Nosrettap


2 Answers

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.

like image 148
nhahtdh Avatar answered Oct 04 '22 14:10

nhahtdh


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.

like image 25
asteri Avatar answered Oct 04 '22 14:10

asteri