The best way to comment your code
Andy Hawthorne • July 11, 2019coding
All developers know that they should comment their code. Yeah, they do. So how come so many still don't? Why do simple comments so often get left out of the source code? Here's the best reasons for commenting your code...
Most editors and IDE's have support for adding doc blocks. You can squirt them in above your class methods.
Your favourite coding software will often pick up parameters and variables for you.
The Sublime text editor has a doc block package you can install. Then, you type
/** followed by a tab and away you go.
So, we know we should do it. Why is it so damn difficult to do?
Solving problems not writing stuff
You've spent hours trying to figure something out. You've tried all sorts to get past this issue.
Then, eureka! You get it working. Meanwhile, the stakeholders are glaring at you to get the next bit done. You move on...
(No comments written).
Read the code, right?
We all like to think we write readable code. No need to waste time writing comments - a decent developer can read the code and figure out what's going on.
I'll do it later, I need to finish it first...
You are busy coding up a storm. This project is going well - you are burning through your sprints at a bonus-worthy rate.
You have this nagging feeling that there is a lot of code - none of it commented. But you know you'll get to it soon...
You will, of course you will...
We've got tests...
Great. I'm pleased for you - honest. Still comment your code, though.
Because... I can run the tests. I can see that there is awesome code coverage.
I still want to understand how you've solved the problems presented for this build.
The obvious way is for me to run the code of course. But I also read the code. I don't want to look at a bunch of classes and class methods that don't make sense (at first). I can read your comments and make sense of it quicker.
C'mon then, what's the best way?
OK, here goes...
Write the damn comments
Do it when you get the code doing what you need. Use a Docblock to remind yourself what's going on. As well as anyone else trying to work on your code.
I'm working on a project built by an external dev team. I've run some stats to discover that 81% of the code isn't commented.
Sure, I can read the code. And yes they provided some manual documentation.
But I would like to read the code and understand what problem was being addressed - right there.
The bottom line...
It is an easy habit to get into. Bashing code out, writing tests and all that jazz.
But remembering the comments is a simple thing that will make everyone's life easier.
Write 'em on the go. That's the best way, then you are explaining your code as you write it.