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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With