The Importance of Comments

Imagine you received some obfuscated code, or code in a different language and were asked to make changes to it by the end of next week. It had no comments and you don't speak the language. First, it'd take you a while to figure out what the code was even doing before you could jump in and make changes to it. You'd curse the previous developer and the horse they rode in on. Turns out it's a lot easier to document how something works as you're doing it than trying to work it out years later. You might not be the last person who touched it. The person who wrote it might not even work there anymore! Some poor bastard is going to have to reverse engineer that mess and you don't want to be around when they do because they are going to be pissed.

You might think that if you write code that other people can't understand, that's job security. No, it just means it's not getting checked in until you comment all that mess to explain why it's doing what it's doing. It's easier to just rewrite it on the spot and sack you than deal with the damage years down the line. You're the developer equivalent of the kid who pees in the pool, so just like the pool, they'll kick you out and be angry as they clean up the mess.

So, how do we fix this?

  1. Comment why your code does what it does. The comment // Multiply total by 1.06 means nothing if I don't know what 1.06 is or why it's doing it! It could be adding 6% tax to a subtotal, it could be adding interest onto a loan, or anything else.

  2. Don't write things in comments that you wouldn't want your boss or the government to see, because depending on your field and circumstance, either might be possible.

  3. Try to do XML comments if possible. IDEs and tools can slurp then up for tool tips and documentation, which will save you time later on. I can't speak for other editors, but Visual Studio will add a blank template for it when you type /// and GhostDoc will take a blind stab at the text based on your method and parameter names.

Remember, someone's going to look at your code months or years down the road when it gets modified or replaced. It may well be you.

Day 4 of #100DaysToOffload

Tags: Programming