Don't tell me how, tell me why!

Bruno Noriller - Jun 11 '23 - - Dev Community

Is it clear this is about comments? If not, wouldn’t it be better if the title were “Comments: Don’t tell me how, tell me why!”?

This is a problem we see everywhere. There are comments that without any context mean nothing. Others you would need to read the whole code (or article) to figure out the meaning and even then it might be misleading or just outdated.

This should probably apply to most cases, but you really want a clear, clean code that anyone can read and figure out what's happening.

That is unless you really need some less readable, more complex code for any reason (usually because of performance). In this case, then please do comment on what is happening and how. But also do…

Comment the WHY!

Why are you using less readable code?

Why shouldn’t I change the order of something?

Why is this here?

Why was this used instead of XYZ?

Depending on what you’re doing, your level, and that of your colleagues, something commonplace for one would be rocket science to another. This is not what this is about.

If you have to revisit the code the next month, you should know what the code is doing by reading it. The thing is: why is that here?

Some pieces can be self-explaining like transformXtoY but why and where should I do that?

I’m also not saying to put a “why” everywhere, but if you revisit the code and spend time figuring out something, or if even after refactoring it someone is always confused about something… then yes, add a “why”.

Not only that, Pull Requests are a great source to find some of those places that need commenting on the “why”.

On the PR someone asked why you did something?

Don’t just tell them! Not only that, don’t do it outside the PR and call it a day.
Refactor the code, add the comment of why it’s there, and then every time someone revisits that piece of code it will be there the why.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .