This Is A Post
A friend of mine suggested to me a few days ago that the recent Apple vulnerability might have been avoided if the (supposed) offending code had been commented. Perhaps, but perhaps not.
Code comments are a tricky business. Everyone knows they’re a “good thing” but that doesn’t mean every comment is a good one. Blindly them in quantity can actually make code legibility worse. I don’t go as far as Uncle Bob, however, who considers every comment “a failure to make the code self-explanatory.”
For me, a great rule of thumb is that code itself should be expressive enough to communicate the “what”, and comments should be used to explain the “why”. An example is instructive:
# If user is root and there is no root password, don't do the thing if user == 'root' and password is None: dontDoTheThing() else: doTheThing()
See how the comment doesn’t provide any information beyond what the code says? Pretty unhelpful. What a developer who’s asked to maintain this code needs is context, like the following:
# By default an installation of MacOS does not set a root password, thus root # should never be used as a privileged account unless a password has been set if user == 'root' and password is None: dontDoTheThing() else: doTheThing()
Much better. A comment like that, and maybe Apple doesn’t end up in the headlines.