Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Condition Simplification

I'm refactoring a code snippet in which I see the following condition that I wonder whether it's simplified.

data.RecordId != 0 || (data.RecordId == 0 && data.SerialNum == "0000")

Isn't data.RecordId == 0 || data.SerialNum == "0000" same of that?

If it is possible, how come? Could you detailed?

like image 537
concurrencyboy Avatar asked Jun 15 '26 07:06

concurrencyboy


1 Answers

yes, it's possible, assuming you had a typo (!= not ==)...

let Wolfram Alpha explain:

https://www.wolframalpha.com/input/?i=simplify%3A+R+%21%3D+0+%7C%7C+%28R+%3D%3D+0+%26%26+S%3D%3D+0000%29

R!=0 ∨ (R = 0 ∧ S = 0)

is simplyfied as:

R!=0 ∨ S = 0

the explaination step by step:

https://en.wikipedia.org/wiki/Boolean_algebra#Laws Distributivity of ∨ over ∧ says:

x v (y ∧ z) = (x ∨ y) ∧ (x ∨ z)

in you case:

R! ∨ (R ∧ S) = (R! ∨ R) ∧ (R! ∨ S)

where (R! ∨ R) is always true and you can ommit it as the 1st operand in the and logic:

R! ∨ (R ∧ S) = true ∧ (R! ∨ S)

R! ∨ (R ∧ S) =  (R! ∨ S)

voilá

But I see another kind of runtime difference that deals with the shortcut evaluation of &&:

if data.RecordId == 0 is false in the longer expression, it will not evaluate the right part with data.SerialNum, which can avoid getting a null ref.

like image 176
Falco Alexander Avatar answered Jun 16 '26 21:06

Falco Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!