I have this if-condition
in my code:
if (a||a&&!b){
// do some stuff
}
with that intial values from my junit test
:
boolean a=true, b = true;
as I recognized later the statement can be simplified to:
if (a&&b)
becomes green: Assert.assertTrue(a||a&&!b == a&&b);
Are there any further simplifications? How could I have recognized that this boolean expression could be simplified?
a || a && !b
is not equal to
a && b
It is equal to just a
.
I suppose that in your JUnit test you used a specific combination of values for a
and b
where the results match, but that does not mean that the expressions are equivalent—and in fact they aren't. A quick way to convince yourself of that is checking the combination
a = true, b = false;
Your original expression clearly yields true
for all cases where a == true
, but your second expression will yield false
whenever b == false
.
As for a formal proof of equivalence to just a
, take the expansion
a == a && (b || !b)
== a && b || a && !b
Plugging into your original expression:
a || a && !b == a && b || a && !b || a && !b
== a && b || a && !b
== a