Well yeah, we should write comments in code to explain what’s happening in a better way.
But before that, why not write self explanatory code?
Programs are meant to be read by humans and only incidentally for computers to execute.
- Donald Knuth
Before we write a comment, give a thought if you can change the name of variable or a function to make the code talk for itself.
I came across this idea in the book called The Pragmatic Programmer. It’s a beautiful book which directly improved the quality of code I write. Haven’t finished it yet, but took so much from it already.
I personally am not a fan of big variable/function names. I also don’t want to spend time coming with a good variable name (second toughest thing in programming). But this single thing helps make quality so better.
It feels amazing when you can read your code top to bottom of the file and you understand.
Better names make you understand the code better.
I used to think longer names make the file size bigger. It’s not true anymore. All modern tools minify, uglify and remove all the code comments to make the file small. Which means your variable names get replaced by a single letter.
Sometimes it happens that the logic itself is complex.
And we can help here. How much ever you try to come up with better names, it doesn’t do a great job of explaining what’s happening.
Comments are our resort here.
The code keeps changing. And we generally don’t care to update the comments. This is when the comments become stale. This will mislead the reader.
This is a reason why you should trust the code more that comments in a code base.
Code never lies.
That’s all for this letter. I hope you’ve had something to takeaway from this.
See you next Tuesday 👋