Obviously, code examples should be on their own page. I usually do a type of manual for my classes in markup language.
- - -
Your code should definitely be as clear as possible, but comments are useful in several circumstances:
1) complex algorithms:
It doesn't matter how clear and easy to read your code is, it won't diminish the complexity of your algorithm. Sure, sometimes this complexity is due to bad planning and architecture, but sometimes there is no way around it. Some algorithms are complex. When you have 10 lines of code accomplishing a really complicated task, it can help a lot to comment that.
2) Exceptions:
The devil is in the details. Usually, a large portion of code deals with exceptions. It's good to comment this. It helps maintainability. If you have a bunch of lines that tackle a tricky problem that occurs in some obscure situation, I'd like to know this information if I was tasked with maintaining your code. Why should I have to read through your code and follow the breadcrumb trail to find out the function deals with something that happens almost never.
3) IDE's and comment parsing
Development tools can be linked with the comments for fast searching through code. Here's a simple example with some comments that describes the first function. I can set my IDE to parse for the comment @uses and quickly find out which functions use which others. I can also generate documentation markup automatically with this data. Essentially, comments can be parsed.
Code: Select all
--[[
This is some Function.
@params none
@returns none
@uses someOtherFunction()
--]]
function someFunction()
end
function someOtherFunction()
end
Obviously, there is such a thing as bad comments. Comments that comment the obvious are bad. The trick is to know what to comment and what not to comment. Saying that comments don't help maintainability is ludicrous in my opinion. Good comments do help maintainability. Go back to some of your code that you wrote 3 years ago and see if helps when there are comments. A lot of times, you'll wish you'll have commented this or that.
As a freelancer, I always look at the code before deciding to embark on a maintainability job. If there are zero comments, I usually say no instantly. I don't want to have to learn all the code and classes if I'm planning on simply changing a few features. I want to figure out where the important stuff is real fast. Time is money.