String.equals() argument ordering

后端 未结 10 1472
太阳男子
太阳男子 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:04

    yoda condition is where oup put the literal in front of the variable.

    word.equals("s") is read as "word equals s"

    "s".equals(word) a human reads as "s equals word"

    Our brains read the first example much better and the code is clearer.

    the only reason imho to use yoda conditions is to prevent assignment as in "if (42 = i)" instead of "if(42 == i)"

提交回复
热议问题