理由
ほとんどの開発者にとってこれらの演算子は次のとおりであるため、演算子&&=
と演算子はJava では||=
使用できません。
例&&=
Java が&&=
演算子を許可している場合、そのコードは次のとおりです。
bool isOk = true; //becomes false when at least a function returns false
isOK &&= f1();
isOK &&= f2(); //we may expect f2() is called whatever the f1() returned value
次と同等です。
bool isOk = true;
if (isOK) isOk = f1();
if (isOK) isOk = f2(); //f2() is called only when f1() returns true
この最初のコードは、多くの開発者がf1() の戻り値が常に呼び出されると考えているため、エラーが発生しやすくなっています。whereが返されたときにのみ呼び出されるf2()
ようなものです。bool isOk = f1() && f2();
f2()
f1()
true
開発者が return の場合にf2()
のみ呼び出されるようにしたい場合は、上記の 2 番目のコードの方がエラーが発生しにくくなりますf1()
。true
開発者は常に呼び出されることを&=
望んでいるため、Elseで十分です。f2()
同じ例ですが、&=
bool isOk = true;
isOK &= f1();
isOK &= f2(); //f2() always called whatever the f1() returned value
さらに、JVM は上記のコードを次のように実行する必要があります。
bool isOk = true;
if (!f1()) isOk = false;
if (!f2()) isOk = false; //f2() always called
比較&&
と&
結果
ブール値に適用した場合、演算子の結果は&&
同じですか?&
次の Java コードを使用して確認してみましょう。
public class qalcdo {
public static void main (String[] args) {
test (true, true);
test (true, false);
test (false, false);
test (false, true);
}
private static void test (boolean a, boolean b) {
System.out.println (counter++ + ") a=" + a + " and b=" + b);
System.out.println ("a && b = " + (a && b));
System.out.println ("a & b = " + (a & b));
System.out.println ("======================");
}
private static int counter = 1;
}
出力:
1) a=true and b=true
a && b = true
a & b = true
======================
2) a=true and b=false
a && b = false
a & b = false
======================
3) a=false and b=false
a && b = false
a & b = false
======================
4) a=false and b=true
a && b = false
a & b = false
======================
したがって、はい&&
、ブール値を置き換えることができ&
ます;-)
&=
の代わりに使用することをお勧めし&&=
ます。
同じ||=
と同じ理由&&=
:
operator|=
は よりもエラーが発生しにくい||=
。
開発者が return のときに呼び出されたくf2()
ない場合は、次の代替案をお勧めしますf1()
。true
// here a comment is required to explain that
// f2() is not called when f1() returns false, and so on...
bool isOk = f1() || f2() || f3() || f4();
また:
// here the following comments are not required
// (the code is enough understandable)
bool isOk = false;
if (!isOK) isOk = f1();
if (!isOK) isOk = f2(); //f2() is not called when f1() returns false
if (!isOK) isOk = f3(); //f3() is not called when f1() or f2() return false
if (!isOK) isOk = f4(); //f4() is not called when ...