逻辑运算中的条件赋值

Conditional assignment inside logical operation

这是 shorthand 一种不好的做法吗?或者任何具有 Java 基本知识的程序员都应该知道在下面的代码中 checkDoSResult 如果 host 不会被重新分配等于 "localhost"?

int checkDoSResult = 0;
if (!"localhost".equals(host) && (checkDoSResult = CheckHost.checkDoS(user+"@"+host, "query"))!=0)
...

你可以拥有这个:

int checkDoSResult = 0;
if (!"localhost".equals(host) && (checkDoSResult = CheckHost.checkDoS(user+"@"+host, "query"))!=0) {
    ...
}

或者这个 (@Arkantos):

int checkDoSResult = 0;
if (!"localhost".equals(host)) {
    checkDoSResult = CheckHost.checkDoS(user+"@"+host, "query");
    if (checkDoSResult != 0) {
        ...
    }
}

两个片段的作用相同,但哪个更容易阅读?我会选择第二个选项。

"any programmer with basic knowledge of Java" 知道某事并不一定使 "something" 成为一种好的做法。

众所周知,条件和循环头中的赋值很难发现,因为程序员的眼睛期待的是那里的条件,而不是赋值。将赋值放在逻辑表达式的 short-circuited 部分只会让事情变得更糟。

当然,任何受过良好培训的程序员都能够 "decipher" 准确表达您想说的内容,但这需要他们一些时间。将条件拆分为两部分,并将赋值放在 if 语句的正文中,这将有助于其他人理解您的意图,这比节省几行代码更重要。