top | item 42707212

(no title)

venning | 1 year ago

It may be worth pointing out: these are equivalent comparisons when testing for even numbers but cannot be extrapolated to testing for odd numbers. The reason being that a negative odd number modulus 2 is -1, not 1.

So `n % 2 == 1` should probably [1] be replaced with `n % 2 != 0`.

While this may be obvious with experience, if the code says `n % 2 == 0`, then a future developer who is trying to reverse the operation for some reason must know that they need to change the equality operator not the right operand. Whereas, with `n % 1 == 0`, they can change either safely and get the same result.

This feels problematic because the business logic that necessitated the change may be "do this when odd" and it may feel incorrect to implement "don't do this when even".

I really disfavor writing code that could be easily misinterpreted and modified in future by less-experienced developers; or maybe just someone (me) who's tired or rushing. For that reason, and the performance one, I try to stick to the bitwise operator.

[1] Of course, if for some reason you wanted to test for only positive odd numbers, you could use `n % 2 == 1`, but please write a comment noting that you're being clever.

discuss

order

userbinator|1 year ago

I really disfavor writing code that could be easily misinterpreted and modified in future by less-experienced developers

That's their problem. Otherwise you're just contributing to the decline.

notfish|1 year ago

In what languages is n % 2 -1 for negative odd numbers?

Edit: apparently JS, java, and C all do this. That’s horrifying

jagged-chisel|1 year ago

Horrifying? It’s mathematically correct.