Tuesday, July 19, 2005

How to Write Comments

Last edited: 2006 January 16

Should I write comments? What is good comment? Is it possible to write comment for a class in 5 minutes? I would discuss these questions. I would be happy if, after reading, you will be thinking that good comments are an important thing to your project success.

I must admit that I hated to write comments. I was finding them boring and unnecessary. And the worse thing is that I was afraid that during my design some of my methods or classes might go away together with my time spent for writing my good comments. So the first thing I would discuss is


Why?

Here is the first reason for comments. Comments can make your design clearer. You could mark the class with its responsibilities using comments. You can check then how much your class respects its responsibilities, and that it don’t do something which is not its responsibility. Moreover, you can check how much your class respects Single Responsibility Principle and make some decisions to improve the design.

But I think that primary reason which can force you to write comments is to make your code understandable for others. The rule is simple. If you will hide your code for forever - nobody is going to know if it is commented or not. As soon as you are going to share your code with some other person - unless you are not writing it all together from the beginning - he or she will be happy to see your class comments.

Of course you could be happy to explain it to everyone personally. But you want to avoid phone calls asking what your class does while you are on vacation.

Updates are here!
Some person recommends to comment hard things. Absolutely.
Many people w
rite comments for themself. Hire them now.

Do you know any other reasons which make you to start writing comments? If yes - I will be happy to include them here. Personally I find an important reason to have a good rest on vacation. So the next question will be -


How?

What is good comment? Should we judge how good the comment is by its word count? Should we have each method commented? I would say we don’t, or else our comments could end up time-consuming for us and being boring for our readers.

Antipattern
It’s so easy to mark a class with extended description of its name. We end up with class TransactionManager marked as Represents a Transaction Manager. Would this be descriptive enough? No sense to include this in comments at all. I can read a class name by my own. I would be more happy to see TransactionManager marked as Manages (creates, disposes and provides) transactions.
Personally I find very useful an old proven approach for class comments. CRC cards was used for a long time (since at least 1989) and hugely adopted with modern techniques like Agile Development (see http://martinfowler.com/articles/designDead.html and http://www.agilemodeling.com/essays/agileModelingXP.htm). We can take two good things from there and supply our comments with: class responsibilities, and class names our class is planned to communicate with.

Note that OO design tells our class to respect Single Responsibility Principle. Here is where your comment becomes an important design tool. If you find it impossible to name your class’s responsibility with a single combination of verb and noun – it is a good chance your class is taking too much on itself and should be split. One trick here is - use of manages helps.

Antipattern
Someone might want to describe here how other classes are going to communicate with our class. I would move this information into corresponding class.
We should end up with class comments which are pretty short but descriptive enough. And what about method comments? No clear recommendation for now. I would recommend to name a method as much descriptive as possible. It could make its comment unnecessary. I would mention some exception situations however. For example, I would describe what the method does if no item with given key available. Will it return null? Will it throw an exception?

Ok! Now we know which kind of comments we are going to write. Now the question is


When?

I dislike doing something which will be thrown away. I dislike writing comments which will be thrown away. During my design, I create new classes, play with them, throw them away and create new instead. I would find a way to save my time and write a comment when I have a decent hope my class will remain within the system.

The point to start writing comments is... when the code is ready to be presented for others. This could be the time before commit to a main source repository, or insert your case here. For this time, I have pretty stable class design, and good chance my comments will live long. I am pretty sure with my class’s responsibilities and what classes it will collaborate with. I can spend as much as 2 minutes writing this information as a class comment. Everybody’s happy!

84 Comments:

Blogger Godsdaughter22 said...

Interesting entry. Feel free to comment on my blog when you have the time. I would like to get to know you more. Such as schooling, family, age, where you live, religion, etc.

Wed Jul 20, 03:44:00 PM GMT+3  
Blogger 10048 said...

Interesting post. Somehow some developers don't get it. I am old school and the question of commenting your code has been around a long time. As a manager of developers on many large and small projects I would not tolerate undocumented code. The developer is not writing code for himself (assuming he is in the employ of a company,) he is getting paid to do a job. If the developer can not spend time to document his code (instinctively) then I would not expect him to last very long on a project.
Could you imagine in todays "open source" culture that an application's code not be documented? This would set our industry back 30 years.

Wed Jul 20, 04:19:00 PM GMT+3  
Blogger Denis Krukovsky said...

Open source project will definitely have a good advantage if its code will be well understandable. In this article, I tried to show several problems which stops from writing comments, and how to deal with them.

Fri Jul 22, 03:53:00 PM GMT+3  
Anonymous Richard C Haven said...

Beginning coders comment nothing;
Novice coders comment the obvious;
Experienced coders comment the reason for the code;
Master coders comment the reason for the code not used

Tue Nov 22, 09:40:00 PM GMT+2  
Anonymous JimS said...

Good thoughts on comments. As an embedded developer attempting at times to use open source stuff I would plead with the community to please comment your routines. In the embedded world a lot of times we don't have a POSIX environment or sometimes even an OS. Trying to adapt open source stuff becomes a challenge because we cannot just configure make... We have to re-write the code to adapt it to our environment. The greatist help here is comments on each of the routines (methods) so we can see the gazinta's and gosouta's what they do and what the routine does. I've given up on a number of interesting open source tools or libraries because they don't do this and I don't have the time to decode cryptic routine parameters and try to guess what the routine does and what the output might be.

Anyway, document your stuff and your project might just end up in every parking meter on the planet...

Wed Nov 30, 06:08:00 PM GMT+2  
Anonymous Oscaruzzo said...

You say But I think that primary reason which can force you to write comments is to make your code understandable for others.

Actually I think the primary reason is to make your code understandable to yourself and actually I tend to write comments before I write the code itself...

Wed Nov 30, 06:14:00 PM GMT+2  
Anonymous Broofa said...

I would disagree that the primary reason for commenting is to make your code understandable to others . Yes, it is a nice (and necessary) byproduct, but the primary reason Is that the act of documenting will improve the quality of the code you write. This sounds strange, but it's much harder to document poorly written/designed code. Thus, you become much more aware of the inconsistencies and design flaws, and tend to avoid them.

More from me on this subject here

Wed Nov 30, 06:19:00 PM GMT+2  
Anonymous Anonymous said...

I like milk

Wed Nov 30, 06:29:00 PM GMT+2  
Blogger Neil Cherry said...

I'm an old time assembly language programmer (I do hardware) and comments are extremely important. The first comments are documentation that I gather from elsewhere. Then the steps to do something manually. Then I describe the routine, function, whatever. My 'main' routine usually has few comments as the names are self describing (tend to be high level) such as get_cli_options() or setup_daemon() (for those that use C). The actual comments start in the sub files where I've put together an API. The further down you get the more into the bits you get.

Wed Nov 30, 06:30:00 PM GMT+2  
Blogger The Absurd Theist said...

"But I think that primary reason which can force you to write comments is to make your code understandable for others"...I agree with Oscaruzzo...I AM the Other...6 months from now I may have to revisit my own code. No ones mind is perfect and cannot remember everything it ever wrote. Comments are SELF-reminders.

Wed Nov 30, 06:30:00 PM GMT+2  
Anonymous Anonymous said...

"Comments can make your design more clear." You mean, "clearer"?

Wed Nov 30, 06:33:00 PM GMT+2  
Anonymous Anonymous said...

ewww... I forgot what I wanna comment :P

Wed Nov 30, 06:42:00 PM GMT+2  
Blogger Denis Krukovsky said...

Thanks for your comments and grammar fixes everyone. Definitely one of the important things comments can give you is clearer vision of your design! You might even trigger design changes as long as you write comments.

Wed Nov 30, 06:43:00 PM GMT+2  
Anonymous Anonymous said...

Hi.

Interesting read, but a few comments.

Disclaimer: I am a teacher in embedded systems/robotics/computer architecture/...

When I teach programming, an integral part is spend on how to comment code. It is not only important, as you said, to explain code to others. It is also important to keep remembering what you actually did with the code you wrote several months after you wrote it and after you have moved on to a different project.
Secondly writing your comments before you write code (as some other poster here mentioned) can lead to a clearer/more structured implementation of your routine/method/class whatever. It can help you to think about how to write the code the best way possible (i.e. design code, not 'hack it together'*). A clear overview of the arguments a function will take and what it returns can lead to a cleaner implementation of the code to do the actual work.
If not, write comments as soon as some part is 'finnished', whatever that means.
And by the way, keeping your comments up to date should be a part of the code maintenance process.
In the embedded world especially (as again someone mentioned here) it is very good practise, and luckily very common, to see very good code commenting. To see an excellent example, get your hands on the uC/OS-II source written by Jean J. Labrosse.
Lastly, it is my opinion that well documented/commented code looks better than non-commented code.

* Use of the word 'hack' due to better alternative, but you get the point, no need to point it out to me how wrong it is for me to use the word in this context ;-)

P.S. English is not my native language, so sue me for my spelling/grammar mistakes. I will reply to your allegations in my native Flemish, or even the language of the country where I am now, Finnish :-)


Best regards and happy holidays,
Johan

Wed Nov 30, 06:46:00 PM GMT+2  
Anonymous sprezzatura said...

A programmer doesn't truly learn the importance of comments until he has enough experience under his belt to have been in the horrible situation of staring at code he wrote years ago... and not understanding a thing!

I like writing comments. Kind of the icing on the cake.

I wish my development environment would support fancy typography in the comments: fonts, bold, tables, etc.

Wed Nov 30, 06:46:00 PM GMT+2  
Anonymous Anonymous said...

The only effective way I have convinced someone to comment their own code is to present them with a lot of code with which they must work that is poorly commented. After an hour or so of using their editors find tool they have been convinced that good comments are the path to nirvana.

Wed Nov 30, 06:54:00 PM GMT+2  
Anonymous Anonymous said...

I comment before I write the code, the comment describing the contract for what I'm about to write. It's good to comment on preconditions and post conditions.

Within the code I find it good to comment on why some things are done the way they are, or if its complex refer the reader to some reference or design material. A block comment called "Calculate the determinate of the matrix" can be quite nice. Not had much need for that recently as more and more of the complex stuff is done in libraries nowadays.

A lot of code nowadays can be autocreated. If the generator were to pass comments from the source definition into what it creates then it would help with things like intellisense. Unfortunately the one I'm using at the moment doesn't.

Combine this with a tool that complains bitterly if something is missing a comment and you get problems - compiler output with hundreds of warnings that if you tried to fix, your work would be overwritten next time the code generator runs on next compile. All these warnings hide the really important "variable used when not initialised" that you really need to see.

Should you comment a method that implements an interface or and abstract method if the comment on the interface or abstract method's comment is enough?

Javadoc and Eclipse are quite sensible here. Eclipse generates a non-Javadoc comment, and Javadoc uses the interface's comment.

NDoc on the other hand insists on a comment on the implementation which is a real pain as keeping all those identical comments in sync is hard - and typing "Look at interface foo" is pointless.

Wed Nov 30, 07:07:00 PM GMT+2  
Anonymous sebastian said...

Ehh... all of that sounds rather complicated and isn't what I've experienced.

Remember, comments are not documentation. Writing a few comments here and there or hundreds of them won't necessarily make your code more understandable.

As a rule of thumb, use comments to excuse or blame. If you're finding other reasons for needing comments, I'd say there's a good chance your documentation isn't sufficient or your code sucks and is too cryptic for another to grasp -- in which case comments probably shouldn't be your largest concern.

Wed Nov 30, 07:21:00 PM GMT+2  
Anonymous Mario said...

Last thing I had to do in my last project was to complete and translate to Spanish all comments/javadoc. I even had to document other's code. During that process I discovered that some comments were a little difficult to write, like the ideas didn't fit quite naturally. Then I realized that the code wasn't as good and simple as it should be.

If I refactored the code in a way that the comments and docs were simpler that would mean that the code would represents the ideas behind it in a more elegant manner. And I think it will represent better code.

If you cannot easily explain what you are doing...something is wrong (either with your doings or you) ;).

Totally agree with neil cherry: Assembler without comments it is worhtless ( or a good trick to keep your job).

Wed Nov 30, 07:29:00 PM GMT+2  
Anonymous dmitry said...

The main reason to comment is to understand the reason for writting the code. If you can't come up with clear comment for an API - don't write it. It means you don't understand the task at hand. So - originally write comments that make you better understand design of the API. Add comments latter to expand original so other will understand you.

Wed Nov 30, 07:32:00 PM GMT+2  
Anonymous Nick the Coder said...

I agree with most of what you said, but one thing to take into consideration is the time when you should right your comments. I tend to write mine as I code or else sometimes when I come back through a larger class I can not remember the exact reason I did everything I did... this also makes debugging a lot easier.

Wed Nov 30, 07:39:00 PM GMT+2  
Anonymous Stephan Heuscher said...

You forgot the most important reason of all: I write comments so I will understand what I've done (and what the code does).
In one or two months from now, you will have no idea what the code does.

Wed Nov 30, 07:41:00 PM GMT+2  
Anonymous Anonymous said...

Don't comment your code if you wana keep your job ;).

Wed Nov 30, 07:51:00 PM GMT+2  
Anonymous Anonymous said...

I have been in the telecom software industry for 16 years designing and maintaining software applications with millions of lines of code and a 10-20 year lifespan. I have worked through the transition from procedural to data abstraction, and have personally struggled through all the challenges. Good comments increase quality of applications and the productivity of developers for applications with long life spans.

One interesting characteristic of OO development is that the design is performed from a static "data" perspective, but diagnosis is done from a dynamic "functional" perspective. In my experience, it is the ability of an individual to translate between the two modes that determines their effectiveness.

While this translation is trivial in some applications like a washing machine or ATM, where the classes implicitly represent functionality(e.g. card reader). It presents a formidable challenge in transaction based systems where classes represent a tiny piece in a heirachy of logical abstractions with no implicit association with external functionality or context within the system.

In conclusion, good comments should mitigate the risks inherent to an OO methodology. This can be achieved by writing comments that provide the reader with what purpose the class serves in terms of the system context as well as assist them on the translation between procedural and data centric analysis.

Wed Nov 30, 07:58:00 PM GMT+2  
Anonymous Anonymous said...

Generally good advice, thanks. This article does however, point out that most engineers are not good writers. Learn some grammar people!

Wed Nov 30, 08:00:00 PM GMT+2  
Anonymous Anonymous said...

As an aspiring programmer (C#), I find it is important to get in the habit of commenting code.

I know the importance of this as a reslut of the many aquisitions in which our current code (VB) was ridiculed and scrutinized for lack of comments.

BTW - I am learning programming for fun - I am networking geek by trade! :D

Wed Nov 30, 08:03:00 PM GMT+2  
Anonymous Anonymous said...

"Don't comment your code if you wana keep your job"....in seven years of professional coding, I've seen a lot of people attempt this strategy, and every one of them eventually got fired.

At some point, management decides that the pain you will continue to inflict in the future exceeds the pain of transition. Also, bear in mind that at some point, your application starts to become obsolete, and nobody will want to give any new projects to you.

Meanwhile, people who write clean, well-commented code keep their jobs because they make everybody happy.

btw, a wonderful example of well-commented code is the source of SQLite.

Wed Nov 30, 08:05:00 PM GMT+2  
Anonymous Anonymous said...

This is actually 1/3 of a research paper I am finishing now. We compared very successful open source projects to student projects. We found a very strong consistency of both length of comments and how often comments occur across all six open source projects we analyzed. Using this data we looked at student projects and in many respects the student projects comments are much shorter and not as frequent. And as a side note, we analyzed comments, global variables, function calls, and out of everything commenting was definetly the most consistent across all of the projects

Wed Nov 30, 08:07:00 PM GMT+2  
Anonymous Doug said...

For my money the best reason to comment your work is not for others, but for myself. When I look back at something I did more than a month or so ago, it might as well have been done by someone else. My comments are often the only clue to what I was doing or thinking at the time.
As Oscarruzzo said, I comment first, then use the comments to help me with my structure.

Wed Nov 30, 08:08:00 PM GMT+2  
Anonymous NRhettleguest said...

Let's cut to the chase - comments should not explain CODE to other, but establish the CODE's structure and define operational stages. Attempting a deeper explaination means spending valuable time in comment management during debug sessions/trial code development. Not spending the time to manage eloquent comments leads to distrust and disuse.

Use block comments for File/Function headers and establish Name, Purpose/Responsibility, Developer, Date. Make some attempt at I/O, but this usually fail over time.

Use code separation comments to document the different stages within a function - limit to 7 but preferably 3 sets per function.

ONLY use inline comments to establish a correlation between data elements. Explaining data elements is also OK but not imperative.

Wed Nov 30, 08:13:00 PM GMT+2  
Anonymous Anonymous said...

I also like milk

Wed Nov 30, 08:23:00 PM GMT+2  
Anonymous Alex said...

I tend to comment before writing any code: since I mostly write either shell scripts or code for dynamic web pages (PHP is my preferred languate), I generally write out most of the comments as a layout. For instance:

# Section 1 -- check to see if the command line
# arguments make sense.


# Section 2 -- deal with the -h or --help flags.


And so on. In a lot of cases, if I try something and it turns out not to work, I'll comment it out, then add an explanation. ("This turns out not to work because I'm an idiot. I can't insert this value into the DB because it's a string being inserted into a field that has type int! I rewrote this below to do more checking to see whether the data-type is correct").

That way, if I'm trying to do something similar in the future, or if I look at the code and wonder why I wrote that routine in a way that looks more convoluted than it needs to be, I can see my reasoning and why I didn't do it the simple way.

Wed Nov 30, 08:31:00 PM GMT+2  
Blogger Dedly Wombat said...

Code says HOW something is being done. Comments say WHAT is being done, and WHY it is being done. Comments and code illuminate the problem space and the solution space, respectively, and obviously their perspectives are different, which provides a huge help during debugging and maintenance.

Wed Nov 30, 08:33:00 PM GMT+2  
Anonymous grizzled said...

Some advice from a grizzled systems engineer.

Avoid comments.

If a particular piece of code needs comments, first try to reorganize the code lexically and syntactically: apply proper formatting and whitespace and use sensible variable names. It should be a lot more readable now.

Still not immediately clear what the code is doing? Then reorganize your code structurally: move loops and if/else blocks into separate functions, add descriptively named variables to hold the results from complex expressions, strive to replace complex if/else and switch/case blocks by input->action mappings.

If that still doesn't quite work, reorganize your code architecturally: scrutinize the data flow, design a sane API with sensible objects method names. If necessary, go back to the client and verify that you actually understand the problem.

Finally if the code is still not self-explanatory, take all the reasoning that went into the reorganization effort, and use that as a huge big comment block.

Wed Nov 30, 08:37:00 PM GMT+2  
Anonymous Anonymous said...

Two things:

First, comments are useful even if you are hiding your code forever. I can't tell you how often I've come back to an old piece of code, intended only for my own use, and been confounded by its obscurity or pleased to see an explanation in a comment. It makes a difference. It's also a good way to force you to think about what you're doing before you do it. (Even better are languages that allow you to express some of these things in the language itself, so that they are additionally checked by the compiler!)

Two: I'm surprised you didn't explicitly mention pre- and post-conditions, since this has been known for years. When documenting a function, it's critical to state precisely the conditions under which it will work, what it does, and what state of the world it guarantees after being executed. Being specific here helps for the person who wants to call your function, but is even more important for blame assignment: when the program goes wrong, it's important to be able to figure out WHY. Is it the caller or callee? Being able to see that a function is called without its preconditions, for instance, would blame the caller. Seeing that the function doesn't meet its stated specification in a corner case would blame the function itself.

Wed Nov 30, 08:41:00 PM GMT+2  
Anonymous Anonymous said...

I tend to use a lot of comments. Comments not only help you figure out what's going on, but if you are keeping your code organized, then you can use comments to find your way around the code.

Face it - Most IDE/Code editors have syntax highlighting... It goes a lot easier finding a big green comment saying "// interface Drawing starts here" than it does looking through code which is poorly sectioned off. Object Oriented design has done much to alleviate this need, but the need still exists.

Then there's TODO Comments... After you've flow-charted something, or designed something big in UML, etc.... you can place TODO comments to outline the functionality you need to follow in code. Following your design documentation ensures that your code will fit in with everyone else's bit of code.

And, a deleted comment in a deleted code block was still useful. I don't know how many times I've written a comment for what I'm about to do and realized that "This isn't going to work the way it is written". Comments can help you find flaws in your design documentation.

Wed Nov 30, 08:46:00 PM GMT+2  
Anonymous Anonymous said...

You ask, "Do you know any other reasons which make you to start writing comments? If yes - I will be happy to include them here."

When I code, one thing that always triggers a comment in my code is "did I get stuck?". As an experienced programmer, I don't get stuck on the easy stuff. e.g. I can read API docs and if its in there, I don't get stuck. So no comments. Go read the API.

But if I find a bug in the API docs, or if I have to cross reference some arcane document, then the comment will include enough info to reconstruct the document chain or ideas which are necessary to understand why for example an index starts with -1 instead of 0 (there is a bug in the offset algorithm which we don't own which for now adds one to the start index... who knows why, but it happens)

Anyway. That's it. If you have to spend a lot of time getting past some coding aspect of things, I always document the "aha!" or the insight which would have eliminated the need to spend all the time researching at th time.

Wed Nov 30, 08:47:00 PM GMT+2  
Blogger N3twrkM4n said...

I can feel your 'pain' regarding comments. When programming anything (even XHTML, CSS, DHTML) I provide comments to most things.

I tend to discriminate against small comments, and most of the time only comment my functions and what they do.

Sometimes if the mood strikes me I comment where they are called if it seems vague. Great post!

Wed Nov 30, 08:55:00 PM GMT+2  
Anonymous Andrew Moyer said...

Due to the pace at which we must develop, and our coding style which is very clean and self-descriptive, we rarely document our code. We're dealing with PHP using some high powered libraries I developed (which ARE commented.) Most of the scripts are short and sweet, and their content is enough documentation. This is an issue that we battle over often. I say, for posterity, we must document... and my boss says that's fine, but the deadlines we face make it impossible. We do, however, comment whenever possible... it's just that it usually turns out to be less than 10% of what my professor in college insisted we do.

Honestly, I never have any problems reading code without comments. I read code just like I read English, so most of the time I just skip reading the comments anyways because the code itself gives a more complete description.

Comments are good if not essential for more n00bish people though.

And yes, I've been involved in MASSIVE enterprise projects that have spanned over 5 years of development, upgrades, migration, and maintenance, and I've never struggled because of lacking comments.

Kinda a moot issue. It's all about personal style and employment requirements. Here, it's kinda the opposite of what you'd expect. The developers suggesting more time to do it "right", but the higher ups saying, "too bad, just get it don ASAP and move on." Some companies have a person whose sole purpose is to comment code and document its useage.

I do love looking back in my code from 4-5 years ago and reading a section that says something like, "OMG HACK!" or "Redo this later" -- it never gets fixed when you're an internal solutions developer ;-)

-@

Wed Nov 30, 09:02:00 PM GMT+2  
Anonymous mike-m said...

Why another reason is because I need to recall me what the code was written for. So comments are not only util for other people, but also for me self. It's pretty much appreciable to read 1 or 2 lines unlike some lines from the code.

Wed Nov 30, 09:08:00 PM GMT+2  
Blogger dot cpp said...

code should evolve from comments, as shown by OOD (object oriented design) specs. read:
http://www.cs.uwc.ac.za/77.1.html

if you have adequate stub code and algorithm descriptions you don't still need to add comments - can simply write the code around the descriptions.

seems "more" logical.

Wed Nov 30, 09:15:00 PM GMT+2  
Anonymous Anonymous said...

@grizzled: If you are commenting about how a particular routine works, I agree, it's redundant. But a good comment tells how the routine fits into the larger structure, and no amount of code reorganization is going to do that for you. Download the SQLite sourcecode, and ask yourself whether it would really be as easy to understand what's going on without the comments.

Wed Nov 30, 09:16:00 PM GMT+2  
Blogger N3twrkM4n said...

Good post. I generally only program in my free time but my professors at college used to require us to have comments or we ran the risk of failing the project.

In lieu of that I usually comment everything to some extent. Functions get commented more, because there is more to explain; while 'calls' usually only get a couple words if that.

I find myself often commenting my CSS,XHTML, and DHTML as well, even though some would say it's not all too necessary.

Wed Nov 30, 09:18:00 PM GMT+2  
Anonymous BigA said...

comments are for the weak minded, a true hacker will just read the source and compile it in his brain. besides its usually more fun to rewrite things after a few years anyway.

Wed Nov 30, 09:21:00 PM GMT+2  
Anonymous Anonymous said...

My feeling is that the best style for comments is a paragraph at the top of a short block of code (say a page) that clearly describes the functionality of the code. I don't like having comments mixed in with code.

Wed Nov 30, 09:26:00 PM GMT+2  
Anonymous Anonymous said...

The design (descriptive models etc) and following that, the implementation should "speak" the obvious language to anyone who reads the code. The developer should know exactly what the class does before he/she has a first glance at the source code. If I need to read code and embedded comments to understand what a class' responsibility is, then your design is fairly pedestrian if not entirely pathetic. I apoligise if I sound supercilious, but bad design / architecture is almost entirely the cause for 95% of the used/unused software littering the sidewalks.

Wed Nov 30, 10:20:00 PM GMT+2  
Blogger Greg said...

This comment has been removed by a blog administrator.

Wed Nov 30, 10:43:00 PM GMT+2  
Blogger Greg said...

It is possible to write your code without using comments.

I have found that using proper names for variables and methods along with having the each method properly refactored works the best.

This also enables you to see the abstract in your code that allows you to properly move towards using patterns in your code.

My Guidelines

* If you feel the need to write a comment - refactor your code so the comment becomes useless.

* Comments lie over time

Wed Nov 30, 10:44:00 PM GMT+2  
Anonymous Evan Bell said...

Adopting a commenting style like javadoc has other advantages. It works with doxygen and enhances the contextual help in editors like Slick Edit( including hyperlinks and fancy formating ).

Wed Nov 30, 10:49:00 PM GMT+2  
Anonymous Ilfak Guilfanov said...

Being a lazy programmer I comment only when I see that the time spent writing the comment is less that the time I (or someone else) would spend trying to understand the code.

This is the only rule, and it works for me.

Wed Nov 30, 11:05:00 PM GMT+2  
Anonymous Anonymous said...

How to write unmaintainable code

Wed Nov 30, 11:15:00 PM GMT+2  
Anonymous Richard Murnane said...

Comments are there to tell the reader the intent of the code. All that reading the code itself can tell you is what the code actually does. One generally would have no reason to read the code unless there was some discrepancy between the intent and the action; having the two detailed in the same place is A Good Thing [tm].

Wed Nov 30, 11:57:00 PM GMT+2  
Anonymous Larry said...

Consider this article as code. What lies 'between the lines' is open to interprtation. Note all of the comments on this article/code! I now understand the orginal article better. How a class/function works should NOT have to be inferred. Without comments, inferences are drawn and errors introduced in the main program flow - the first step towards a debugging nightmare. Think of commenting, whether separate and distinct or part of a naming convention, the first line of defense against debugging hell. Unless you like to debug, then I think you need therapy - or you need to become a therapist. The last thing I want to do is re-learn why I wrote a class/function in the first place by having to re-trace the logic through it because there are no comments! Kinda defeats some of the advantages of OO programming. Comments are no less important to the language you are using than it's syntax.

# inherited by class MySanity which extends class LifeSpan
$timeCommenting = $timeDebugging/2;

Thu Dec 01, 12:00:00 AM GMT+2  
Blogger Matt said...

A QA point...

I seriously want to throttle my developers who don't comment their code. I have the opportunity to look at their code sometimes, and not being an experienced Delphi developer, I need occaisional direction as to where the code is going or what it's supposed to do. The comments come in handy when testing; I know what I'm supposed to be testing, and if commented correctly, what changed without resorting to a diff program. Very handy.

Thu Dec 01, 12:09:00 AM GMT+2  
Anonymous Anonymous said...

Comments are for your own good and yes, they are needed for others to understand what your code does. Comments should be written before any code is written. Think of it as an outline. First do this... Next do this... Last do this... Writing comments first will allow you to gather your thoughts and convey them clearly through code. Any one that does not believe that spending atleast some of your time to develop sound comments on the front end will save you loads of time on the backend simply has not worked on a large project. Just my 2 cents.
Everyone use comments...
-jmm

Thu Dec 01, 12:35:00 AM GMT+2  
Anonymous Chris Maguire said...

Oh man, I sooooo needed this article! I'm putting together the code standard for our department and the main reason for the standard is to get one developer to comment!

I sent this quote on to my fellow developers:

"Richard C Haven said...

Beginning coders comment nothing;
Novice coders comment the obvious;
Experienced coders comment the reason for the code;
Master coders comment the reason for the code not used"

It seems that there may actually be reasons for not commenting (e.g. language, IDE, 133+n355, etc.) and I'd be interested in encountering a situation where commenting didn't help.

I've been employed as a coder for a little while and for me trying to be 133+ has just lost its novelty. I'm not a compiler and the stress of deadlines and the frustration of absolutely retarded code takes all the fun out of being able to read code without comments. Yes, I could read your code, but I don't want to: I want to jump in your code, find out how to fix it, work with it, whatever, then "mark" my territory with a comment and run away, forgetting I ever had to touch your dirty code.

I'd like to add some reasons for commenting that I don't think have been mentioned:
- you can help others program better by telling them why you did what you did (there are always people more junior than you)
- you can make yourself laugh months and years down the road will silly/sarcastic/rude comments (work should be fun! Too bad it's so much work). Throw in some ficticious variable comments in the comment header and see if anyone notices (FurryWoodlandCreature for instance). Adding quotes is fun too. - when working on multiple projects and fixing bugs across projects it saves "task switching" time: the time it takes to "get out" of one project and "get in" another. I hate spending an hour refreshing my memory on what a coworker's complicated uncommented code does. For me, I like to know why the original developer did what they did so that I can glean business rules, gotchas and limitations from the code.
- Finally, some coders just suck. Therefor if I think someone's code sucks then someone else probably thinks the same of me. So if I'm longing for some comments from them (the crappy coders) then they (the better coders) might be wishing for some insight from me.

Thu Dec 01, 12:40:00 AM GMT+2  
Blogger Stephen said...

Two of the easiest to read chunks of code I've ever encountered were essentially uncommented. One, the 1980s BSD version of tar(1) was around 750 lines. Outside of the odd argv parsing, it was very straight forward.

The other was pretty complicated. It included network server code and supported asynchronous I/O to multiple simultaneous channels, in an era when that was a new thing.

My metric on ease of reading these codes was simply time. Reading was quicker because there was less to read.

If the code doesn't match the comments, chances are both are wrong.

All this said, this isn't the style I use. My style hasn't changed significantly since the mid 70s.

I disagree that the comments are not documentation. The entire source code is documentation, comments and all. About half the time, its all I get.

Its annoying to get block comments like:
# Name:
# Description:
# Change Log:

with nothing filled in. If they bothered to paste in the comment block, why didn't they bother to fill it in?

Thu Dec 01, 12:45:00 AM GMT+2  
Blogger evilmousse said...

learned discipline on ada? my college forced that too. florida tech in melbourne FL. where was your college?

Thu Dec 01, 12:46:00 AM GMT+2  
Anonymous u24 said...

comments are used to describe the code....

just make sure they describe what the code actually does, not what the code -should be doing-... :-)

Thu Dec 01, 01:17:00 AM GMT+2  
Anonymous Anonymous said...

Being primarily an OCaml coder (the link is there just in case you've never heard of the language, not as spam...), I find it extraordinarily helpful to read and comment the interfaces to modules before ever coding anything. It makes sure I've thought through my code before I start 'hacking away'.

Also, as it has been pointed out already, comments do not suffice for documentation, contrary to what JavaDoc, Doxygen, OCamlDoc and the rest would like to convince you. Design/Implementation docs and a manual are critical to any serious software.

Thu Dec 01, 01:26:00 AM GMT+2  
Anonymous Anonymous said...

An very competant and seasoned programming collegue *never* comments his code, the reason he gives is "it was hard to write, it should be hard to read". Strangely, his code is actually quite easy to understand...

Go figure.

Thu Dec 01, 01:33:00 AM GMT+2  
Blogger repeter said...

I like how when I look at the word "Antipattern" and hit my page down key the next "Antipattern" takes its place ofset by just a few pixels.

I've never coded professionally, so I don't really have anything of substance to say. Informative, though. Great job.

Thu Dec 01, 01:52:00 AM GMT+2  
Blogger Pradeep Arya said...

In my last job, I was forced by management (and later became the enforcer, when I became management) to overcomment the hell out of every single element in the source file. When I say "every single element", this includes every single closing brace, to indicate which construct it was intended to close.

Running a source analysis tool, the result often ran about 60% comments, 40% code. I look back on that job now, thinking two things:

1. Whoever invented syntax highlighting has a permanent spot in my "best friends for life" book. [This was the ONLY way to see through the clutter.]

2. How could top management have developed such an unhealthy neurotic obsession with commenting?

When the company offshored to India, the neurotic commenting standard plus software engineers for whom English was a 2nd or 3rd language really became a fiasco.

I agree that comments are a necessity, but the take away is this: Mae West was wrong; too much of a good thing is NOT that great.

Thu Dec 01, 03:15:00 AM GMT+2  
Anonymous Anonymous Coward Coder said...

Richard C Haven said...

Beginning coders comment nothing;
Novice coders comment the obvious;
Experienced coders comment the reason for the code;
Master coders comment the reason for the code not used

I have to say, this is one of the best summary I have ever read about how code is actually documented, and hereby downgrade myself to "Experienced Coder".

Thu Dec 01, 03:42:00 AM GMT+2  
Anonymous Anonymous said...

Good code should be self-documenting.

This phrase is so true, yet often misused by novinces to justify not commenting their bad/poor/aweful/terrible/noobish code.

Experienced coders comment the reason for the code;

Master coders comment the reason for the code not used


Comments should not be a walk thru of how the code works and execute, as it should be self-explanatory if WELL WRITTEN. If you comment like this, you need to maintain your comments like your code, which often is not done and pretty much useless and verbose.

This does not mean you don't comment. You still need to comment certain design/architecture decisions that are not immediatly clear, why certain things are not done in the usual accepted way etc.

Thu Dec 01, 05:36:00 AM GMT+2  
Anonymous f said...

Thanks for the thoughtful post on comments.

I guess I'm really old school. I can't fathom the amount of discussion in the world about whether or not to comment code. Its like a discussion about whether or not you should put your car keys in the same place each evening when you get home. In some sense it is up to you. Do it if you want, and skip it if you don't. BUT if you don't do it, chances are you're going to waste a lot of time looking for the keys -- you're human. If you share the car with others, even more so (problem goes like N^2 if you share w/ N people). If you drive a car for a living, and toss the keys randomly, your stealing from your company. Same for code. Isn't it obvious?

Now, the use of classes is less obvious to me. Again, I'm really old school.

PS: I kind of enjoy the pun of adding a comment to an entry about commenting.

Thu Dec 01, 05:58:00 AM GMT+2  
Anonymous Anonymous said...

I agree with the need to comment code.

What people haven't talked about is why so many people hate commenting.

When I was in school, and we had to comment all of the code that we turned in, I'd point to "Hello World" and ask what the hell I should comment.

Of course, when I was an entry level software developer and had to try to decipher a three year old script made on the fly (that was never intended to still be in use), I really wished for comments (even though it was pretty simple to the guy who made it).

The question is what level of complexity requires a comment?

Thu Dec 01, 06:22:00 AM GMT+2  
Anonymous Anonymous said...

Summary: Write comments on the WHY. Let the code explains the WHAT by itself.

Thu Dec 01, 07:04:00 AM GMT+2  
Anonymous Anonymous said...

Very good article...

Thu Dec 01, 08:28:00 AM GMT+2  
Anonymous Anonymous said...

Anywhere you have a class with the name "Manager" it should be a good indication you have an antipattern on your hands.

Thu Dec 01, 07:07:00 PM GMT+2  
Anonymous Anonymous said...

personally, I think it all comes down the the Single Responsibility Principle.

Comments are needed and most used when SRP is violated. The "how" the "what" and the "why" is all munged together, so its hard to read.

So before you write your comments, go back thru your code, and see if you can describe what each method does with a single verb & noun. if you can't, refactor until you can. Then ask if a comment is needed. Most of the time, you'll find a comment isn't needed. If you do, refactor again.

If you're worried about whether or not the code is doing its job, check your tests (JUnit, NUnit, xUnit, whatever), and make sure its doing what it is supposed to do! If it doesn't have a test, WRITE ONE!

If you're spending time writing comments before code, write the same thing in a test (NUnit, JUnit, etc). Then you can verify the code does exactly what it is supposed to.

Fri Dec 02, 01:39:00 AM GMT+2  
Anonymous Ransico said...

I think things such as Javadoc are tedious at best... however essential if working in an IDE with several other dev's.

Ive been coding for over 10 years, and I comment as I code within the function, and then write a function descriptor when Ive finished the function.

Slightly off topic.. but function and variable naming is just as important as commenting

Fri Dec 02, 02:48:00 AM GMT+2  
Anonymous Anonymous said...

"The point to start writing comments is... when the code is ready to be presented for others."

Shouldn't that be "write the comments before you write the code?"

Sat Dec 03, 10:19:00 PM GMT+2  
Blogger Denis Krukovsky said...

So we got two extreme opinions here. One is that good code is self-documenting and don't need comments. Another extreme is to comment before coding.

What's best for you?

Mon Dec 05, 08:30:00 PM GMT+2  
Anonymous doug in Seattle said...

The reason you write comments is the same reason you should teach your craft at some point in your career--you cannot claim mastery unless you can explain it (and clearly) to another.

Fri Dec 09, 07:49:00 PM GMT+2  
Anonymous Kartik Agaram said...

The biggest disadvantage of comments in code is that tools can't warn you when they become outdated and incorrect. Misleading comments suck.

I've been using a homebrew system for a while that addresses this issue by making version control software aware of comments. This allows me to gauge the age of a comment when I read it as well as scan later commits for anything that might break it. Check out a brief writeup on this system
here.

Tue Mar 21, 07:00:00 PM GMT+2  
Anonymous Anonymous said...

There is a load of cobblers written about what is a 'good' comment, and what is worthless.
ANY comment in code is a good comment. I couldn't care less if it is stating the obvious, I'm just pleased to see it. I'm just away from staring at 1400 lines of someone elses code. It's beatifully written, neat and indented correctly, long meaningful variable names, BUT no comments, and I haven't a clue what it is doing or why it is doing it.

It is next to worthless

Fri Jan 26, 04:50:00 PM GMT+2  
Anonymous Anonymous said...

As far as I'm concerned, comments are part of the code, since they give context to what is being done. Anything that helps reinforce the idea of the item adds to the reality of it. Be concise with your words and suddenly you have code which is easy to maintain. Cheers.

Fri Mar 23, 09:26:00 PM GMT+2  
Anonymous Tokk said...

I personally hate to waste a lot of time just only to understand a long piece of code that could be easily commented.
I often have to edit or work on long pieces of code, that should have commented to make extensions (and obviously bug fixing) more easier.

I think the point is that a lot of coders, when doing their job, don't think about who will work on that piece of work later, trying to add some features or improving it. Maybe just for matter of time... well, I usually comment all of my work and I do spend a lot of time doing that...

Get back working... :)
Hotel Parma

Sun Nov 01, 05:00:00 PM GMT+2  
Anonymous Anonymous said...

I think the opposite than the author... if you don't place comments right from the beginning, you'll probably loose the whole project structure.
I place comments right when I start.

Sun Nov 01, 05:09:00 PM GMT+2  
Anonymous Sesli sohbet said...

I comment before I write the code, the comment describing the contract for what I'm about to write. It's good to comment on preconditions and post conditions.

Within the code I find it good to comment on why some things are done the way they are, or if its complex refer the reader to some reference or design material. A block comment called "Calculate the determinate of the matrix" can be quite nice. Not had much need for that recently as more and more of the complex stuff is done in libraries nowadays.

A lot of code nowadays can be autocreated. If the generator were to pass comments from the source definition into what it creates then it would help with things like intellisense. Unfortunately the one I'm using at the moment doesn't.

Combine this with a tool that complains bitterly if something is missing a comment and you get problems - compiler output with hundreds of warnings that if you tried to fix, your work would be overwritten next time the code generator runs on next compile. All these warnings hide the really important "variable used when not initialised" that you really need to see.

Should you comment a method that implements an interface or and abstract method if the comment on the interface or abstract method's comment is enough?

Javadoc and Eclipse are quite sensible here. Eclipse generates a non-Javadoc comment, and Javadoc uses the interface's comment.

NDoc on the other hand insists on a comment on the implementation which is a real pain as keeping all those identical comments in sync is hard - and typing "Look at interface foo" is pointless.

Wed Nov 30, 07:07:00 PM EET


sebastian said...
Ehh... all of that sounds rather complicated and isn't what I've experienced.

Remember, comments are not documentation. Writing a few comments here and there or hundreds of them won't necessarily make your code more understandable.

As a rule of thumb, use comments to excuse or blame. If you're finding other reasons for needing comments, I'd say there's a good chance your documentation isn't sufficient or your code sucks and is too cryptic for another to grasp -- in which case comments probably shouldn't be your largest concern. thankss

Thu Dec 24, 06:54:00 PM GMT+2  
Blogger sharma said...

Nice blog i have an idea on a new set of articles on software development. What if I ask everyone on what the next killer web app will be, and start implementing it with publishing daily articles on how to actually write software from scratch.
eb5 visa

Fri Jan 27, 01:55:00 PM GMT+2  
Anonymous chat said...

wery nice thanks askin
Good thoughts on comments. As an embedded developer attempting at times to use open source stuff I would plead with the community to please comment your routines. In the embedded world a lot of times we don't have a POSIX environment or sometimes even an OS. Trying to adapt open source stuff becomes a challenge because we cannot just configure make... We have to re-write the code to adapt it to our environment. The greatist help here is comments on each of the routines (methods) so we can see the gazinta's and gosouta's what they do and what the routine does. I've given up on a number of interesting open source tools or libraries because they don't do this and I don't have the time to decode cryptic routine parameters and try to guess what the routine does and what the output might be.

Sun Jan 20, 02:47:00 AM GMT+2  
Blogger Murat Suna said...

thank you

chat
sohbet
sohbet
sohbet

Thu Nov 13, 07:58:00 PM GMT+2  

Post a Comment

Links to this post:

Create a Link

<< Home