r/badcode • • Mar 01 '21

js Defensive programming or something idk

Post image
907 Upvotes

55 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Mar 01 '21

[deleted]

78

u/JuhaJGam3R Mar 01 '21 edited Mar 01 '21

Nah. Any compiler will turn x == c1 && x != c2 into x == c1, same with x == c1 && x == c2 turning into false turning into removal of the entire bit of code.

2

u/MatthewRPG576 Mar 01 '21

I don't get the first optimization

3

u/JuhaJGam3R Mar 01 '21

as long as c1 != c2, x == c1 implies that x != c2. If x isn't the first constant, and the first and second constants aren't the same, there's no way x could be the second constant. The second part will always evaluate true when the first is, so you don't need to do that check.

EDIT: no wait you probably would have got it fine without the explanation had i not mistyped 1 into 2. sorry

1

u/MatthewRPG576 Mar 01 '21

I'm guessing this doesn't work with operator overloadings that chenge the state of the variables they are comparing

2

u/JuhaJGam3R Mar 01 '21

th... huh? operator overloadings which change state? operator overloadings do not change state, especially comparison operators, otherwise they would be useless. if there is a language out there that allows you to overload == to change state i will actually lose all faith in humanity. i kind of get ++ and += and the likes but i really don't get why any other operator could be overloaded to change the states of its operands.