People -in my honest opinion- tend to underestimate a very important power while coding: Comments.
So, just be honest here;
Why Comment?
First; why not? The reason most people don’t comment their code is because it takes time. But reading lines and lines of code without comments also takes a lot of time… And saying it’s just a couple of lines, ok, but what if these couple of lines grow over time?
There’s a lot of reasons why you should comment, but also, commenting your code can make coding easier for you.
I use comments frequently for multiple purposes:
- To explain my code, why I did something or when it was changed (like ticket number or storyname)
- To explain what I want to do, while writing it. (psuedo code)
- For my todo’s. –TODO Yvonne: …. (one of my favorites hihi).
- Outline my code, if there’s a large block (i.e. loops) explain what the loop is for in general
- Let people know what my procedure / function does and what params to use
- Generate documentation easily
The main reason to comment your code is so you:
- Help your future self / colleagues(why the … did I do this?)
- Have a quick and easy look what the code does
- Easy to help other colleagues that aren’t familiar with the business rules / logic for this part of code
- Know what the last changes are
- Compare version numbers (i.e. for packages) to see if something is on another environment yet
Too much??
Is it possible to over comment your code? Yes. You shouldn’t have more lines of comment overall in compare to your lines of coding, here are some of my best practices;
- For every 1 to 4 lines of code, try one line of comment
- Explain simple code in bulk
- Try to keep your comments plain and simple. The one reading it can also code, so an outline is more than enough.
- Don’t write a complete book about WHY you did it or HOW, but explain structure / business rules
- Don’t comment every “i = i+1;” line, they’ll get it.
Comment Outline
One last best practice… What’s the best way to comment?
For me, I use /**************************/ for block comments. I often use block comments in packages, to tell what the package is for, last changes and if there’s a commit/rollback inside, etc. Also to outline my function / procedure, using the Java doc template.
For all other comments I use –. But always on a new line, and always on top of the code I want to explain:
for rec_record in cur_cursor loop --Here is a loop that does someting
--Here is a loop that does something
for rec_record in cur_cursor loop