Llogiq on stuff

Extent of Intent

Recently I met someone being wrong on the internet (cue relevant XKCD): They thought their code should include no-ops for visual consistency. Allow me to exemplify:

buf[x + 0] += (val >> 8) as u8;
buf[x + 1] += (val >> 0) as u8;

With clippy, we warn on the x + 0 and the val >> 0, because those are operations that do nothing. Of course the compiler will be smart enough to figure it out and remove them silently, but think about it: Does the << 0 really make the code easier to read (let’s not argue here if that pattern is readable anyway)?

My verdict is negative, and I’ll outline my reasoning here:

All non-whitespace token of the code compete for the readers’ attention. Having more tokens as dead weight means other more important tokens get less attention.

Each character making up the code has a non-zero probability to be mistyped (the probability is somewhat lower for whitespace than for tokens). Worse, there’s the chance the mistyped character will be misread. Perhaps someone missed changing the 8 to a 0 while copying. Are you sure you’d find the bug on inspection? Experience with static analysis tools shows that errors of this kind lurk in most larger code bases.

Even if the coder gets it right the first time, if the code is important, it’s likely to need to change in the future. Consider the possibility that in that future, there will be 10 lines of other operations between the two lines above. Or 20. Or even 100. Is it still clear what that code is doing?

Finally, the intent is obfuscated – we don’t shift by zero or add zero, we simply take the values.

One counter argument is that visual consistency trumps parsing effort. While this can be true, in this case we can achieve about the same effect through considerate use of whitespace:

buf[x    ] += (val >> 8) as u8;
buf[x + 1] += (val     ) as u8;

Discuss this on /r/rust or rust-users!