String.equals() argument ordering

后端 未结 10 1432
太阳男子
太阳男子 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.

    0 讨论(0)
  • 2020-11-27 07:09

    There are several reasons not to do it like that, however in the end it depends on you (or the team working on your product) if you think this is bad coding style. Arguments against it are:

    • Strings are rarely null (and you shouldn't make APIs where they are because people don't expect it)
    • It feels weird to put the value you are comparing to first
    • Code style uniformity is important, because this way is the exception, you should only do it, if everyone in your team does it.

    As said I don't think these arguments are very strong, nor is the reason to do it like you. So it is mostly important to just agree on one way as your coding style and stick to that.

    0 讨论(0)
  • 2020-11-27 07:10

    You can write

    if (word != null && (word.equals("s") || word.equals("y")))
    

    instead of

    if ("s".equals(word) || "y".equals(word))
    

    In this case, first one will never cause any NullpointerException, but in my point of view in this case the 2nd one is better, though it is in Yoda Condition

    0 讨论(0)
  • 2020-11-27 07:24

    Yoda conditions (i.e. putting a constant before a variable in a comparison) can be considered bad practice as it makes the line of code less comprehensible. In this specific case however I would state that using a Yoda condition makes the code more comprehensible as you don't have to put a extra null check in front of it.

    0 讨论(0)
提交回复
热议问题