Why comments shouldn't lie: The importance of clear code

This one stings a little, because we’ve all been there. You open a file, see a confident comment saying one thing, and the code quietly does another. Comments age. Code doesn’t lie, it does exactly what you told it to, even if that wasn’t what you meant. Good developers write clear code that explains itself. Comments should add context, not act as crutches. They should explain why, not what. The best comment isn’t “This loops through users.” It’s “This approach avoids redundant DB calls.” That’s insight. Write code that tells its own story. Because when your code and comments disagree, only one of them runs. #CleanCode #Programming #SoftwareDevelopment #Developers

  • graphical user interface, text, application

I get what you're trying to say, and I know your post is about misleading comments. However, let me nitpick on the idea that code never lies. Code can totally lie. Big time. At work, I saw a TypeScript type guard that takes an object and a property name, and narrows the type of the object. When you look at the implementation, you see that it actually only checks that the object has the specified property. The narrowing is therefore entirely dependent on whether the programmer picks the correct property. This code lies about what it does, because it uses the type guard format, but fails to type-guard. (There's also something to be said of a language that allows this kind of discrepancy to begin with, but that's another topic.) To make the irony complete, the comment above the type guard is an acknowledgement that the type guard is likely broken and must be fixed. 😂 There are also other ways in which code can lie, like, for instance bad naming, wrong assumptions about the external resources, etc. So where does this leave us? Everything possibly lies. It's a miracle we can get anything done. 🥹

To view or add a comment, sign in

Explore content categories