String.equals() argument ordering

后端 未结 10 1476
太阳男子
太阳男子 2020-11-27 06:56

I recently received a downvote for using the following in a recent answer:

String word = ...;
if (\"s\".equals(word) || \"y\".equals(word)

10条回答
  •  遥遥无期
    2020-11-27 07:08

    Well, it depends. If in your program "word" should never be null, word.equals("s") may actually be better. If for some obscure reason "word" will become null, you will get NullPointerException. Think about it. If you get exception, you know something went wrong, and you can faster find mistake and fix it. If program will continue to work silently, and produce wrong results, it will be much harder to detect the problem. Actually, you may not notice there is the problem at all.

    It all depends.

提交回复
热议问题