HackerTrans
TopNewTrendsCommentsPastAskShowJobs

venning

1,246 karmajoined 12 lat temu
Christopher Venning

comments

venning
·w zeszłym roku·discuss
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.
venning
·11 lat temu·discuss
DC is definitionally composed of people carrying opinions across the spectrum. Being vocally opposed to those things you list is actually a job requirement for some places. DC's stereotype is a bit unnuanced.