14

CompSci の教授と話をしていたところ、彼はすべての String.equalsメソッドを次のように記述することを提案しました。

"Hello World".equals(fooString);

それよりも:

fooString.equals("Hello World");

これらの行は両方ともコンパイルされますが、最初の方法の利点は何だろうと思っていました。私はいつも後者の方法でそれをやっていました。これは間違っていますか?共通/従来とは何ですか?

4

2 に答える 2

18

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.

于 2012-09-19T00:31:57.230 に答える
13

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.

于 2012-09-19T00:38:14.293 に答える