Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I had a search but didn't find what I was looking for, please feel free to link me if this question has already being asked.

Earlier this month this post was made:

http://net.tutsplus.com/tutorials/php/why-youre-a-bad-php-programmer/

Basically to sum it up, you're a bad programmer if you don't write comments. My personal opinion is that code should be descriptive and mostly not require comment's unless the code cannot be self describing.

In the example given

// Get the extension off the image filename  
$pieces = explode('.', $image_name);  
$extension = array_pop($pieces);  

The author said this code should be given a comment, my personal opinion is the code should be a function call that is descriptive:

$extension = GetFileExtension($image_filename);

However in the comments someone actually made just that suggestion:

http://net.tutsplus.com/tutorials/php/why-youre-a-bad-php-programmer/comment-page-2/#comment-357130

The author responded by saying the commenter was "one of those people", i.e, a bad programmer.

What are everyone elses views on Self Describing Code vs Commenting Code?

share

locked by World Engineer Sep 4 '13 at 2:06

This post has been locked due to the high amount of off-topic comments generated. For extended discussions, please use chat.

1  
@Péter - I did take a look at that one but I was more wanting to get peoples personal opinion between the two, rather than defining comments as code-smells or not. –  Phill Feb 24 '11 at 10:11
2  
I find that article.... horrible to read. Very insulting. –  sevenseacat Feb 24 '11 at 10:23
3  
"Why you are a bad PHP programmer" Answer: Because you are programming in PHP. –  Thomas Eding Apr 4 '12 at 20:27

21 Answers 21

up vote 32 down vote accepted

I prefer writing self documenting code. A guide for this is Clean Code.

This of course does not mean one should never use comments - they have their role, but IMHO you should use them carefully. This earlier answer of mine on SO explains my thoughts on the topic in more detail.

Of course, as @Niphra noted, it is always worth double checking that what I believe to be clean is really understandable by others. However, this is a question of practice too. Back in the uni I wrote cryptic pieces of code simply due to using strange and funny names for all code entities, according to my whim. Until my teacher threw back one of my assignments, politely noting that he couldn't figure out which module was the main :-) That was a good lesson, so I strove to focus on writing ever more readable code since. Nowadays I hardly get complaints from teammates.

share
5  
One of my favorite quotes from Clean Code is that every comment is a failure to express yourself in code. –  Doval Feb 20 at 20:01

At university we were taught to pretty much rephrase every line of code in English with a comment (probably just to get us into the habit of understanding what code actually does, rather than just copy/pasting something and hoping for the best).

Personally, I reckon that clutters the hell out of your code, making it less readable than if it were just comments or just code. I'm a C# coder and the only comments I make all the time are the "triple-slash" comment blocks that are interpreted back to IntelliSense documentation. If I'm feeling especially guilty about a particular way of doing something, orit looks especially cryptic, I'll give a further explanation, but that's about it.

IMO: Self-documenting code is code where variable and method names are given meaningful and contextual names, so that they describe what their purpose is.

share

In that case, it's easy to make a descriptive function. But I've read a lot of code made by good programmers who believed their code was self-documenting, and what had been crystal clear to them was really confusing to me.

$extension = GetFileExtension($image_name);

To get back to your exemple, can I send an array of image names to it, or does it take only one image? Does it support any types of file, or only some of them? Will it secure the string for me, or do I have to do it? If the file type doesn't exist, does it notify me?

Of course, I'm stretching this one a bit. But I remember a programmer who believed audio_bandwidth and video_bandwidth were self-documenting names; turned out audio had to be expressed in bytes and video in kilobytes. Took a lot of time to figure that one out.

share
5  
You're stretching that one a lot. The function gets the file name extension. Nothing more nothing less. Its name says if it takes an array or not (clearly not). I can't think of a method that would rely on the file type to get the extension. Securing the string is the only one that might be incorporated, but I would never expect it because as any PHP dev knows: all user input is suspect, so secure it before you use it. –  Matt Ellen Feb 24 '11 at 9:52
2  
@Matt: The “clearly not” is an indication that you don't do maintenance very often. Being explicit saves much head-scratching (and RTFSource) later on, and it also documents what the original author expected it to do. Whether that's in a comment or in a long function name isn't nearly so important. –  Donal Fellows Feb 24 '11 at 10:01
1  
@Donal Fellows: it says file, singular. What is ambiguous about that? It's completely explicit. –  Matt Ellen Feb 24 '11 at 10:12
4  
The fact that there are now 7 responses from 4 people discussing the obviousness or otherwise of a single function call suggests to me that you need to use comments. It's also highlighted the fact that accurate naming is an artform in itself. –  Ant Feb 24 '11 at 13:12

I don't actually believe in self-describing code. There is more readable code and less readable code, depending on the language, your knowledge of it (as the original author), the knowledge of the guy reading it, and the code function. But no, still ... it should be described with a short comment.

What is clear to me now, that I'm in that area of thinking will probably not be clear to me in a year, when I'm thinking about something completely different and need to use this part of the code again.

So, comment your code. Not every line (good heavens, no) of course, but put a few lines of comment above a function / subroutine / module, or a particularly tricky part and tell in short what it does. You'll thank yourself in a year or two.

share

"Im sorry but your that guy."

I wonder why he does not like commenting :P

Seriously, coding is too much of an art that one could truthfully make such a sweeping statement. Sometimes you need comments, sometimes more and better named functions. Usually both.

Look up literate programming as an extreme style.

share

One does not exclude the other. Even though your code is self-commented, there are times when you may need regular comments to explain why your self-commenting code does what it does.

share
1  
@SK-logic: public <T> void hit(T item); –  Michael K Feb 24 '11 at 15:38

Well you also have to remember something that is obvious or "self-documenting" to you, may not be to someone else...Maybe someone with less understanding of certain functions. So I comment just about everything.

share
1  
Can you give an example. I mean given the example in my original question. "GetFileExtension" whats the point in the comment "Gets the file extension of a given file"? The method has already described what should go into the comment. If the method was named "GetExtension" then a comment would aid in clarifying what the method is to do, since the method is not explaining itself. –  Phill Feb 24 '11 at 13:22

I disagree with that article and agree with you to some extent. If you use good method names, good variable names and small method that do a single thing, the code should be simple to follow.

Just try not to be clever because clever code is horrible read and maintain. Keyword: maintain!

My opinion is that comments should describe the why and not the what. Remember in this hypothetical perfect world, your code is clean enough to allow for easy reading, you don't need to explain what it's doing, but why you chose to do it this way or that way.

If you're using a source control system, you can use the commit message to let everyone (and yourself) know what you did at a given time and more importantly, why.a

share

Well, the thing with self documenting code is that within that function, you would find :

$pieces = explode('.', $image_name);  
$extension = array_pop($pieces);  

which is self explanatory when you have the function name since it's only two lines. When things get more complicated, you either have to wrap every few lines of code in a function with a descriptive name, or use comments where necessary.

I never understood why it should be an or/or matter, instead of and/and. Yes, make your code as much self documenting as possible, and yes, add some comments to the parts that would otherwise be rather unclear.

share

You shouldn't document what the code is doing, but you should document why it's doing it.

No amount of naming trickery will expose the whys and wherefores, so you have to add comments to explain the purpose of the various bits of code.

All the other comments can safely be get rid of.

share

Comments and the self-documented clean code are different. Code is all about how to do things. And comments should cover the why part, which can't be explained in code, whatever your language is. Also, if your language is very limited and you've got no contracts, no static specifications and even no assertions, comments should cover the boundary issues of your code.

share

If you have revisited your code multiple times and still not have found a way to make the intention clear to some one who knows the domain. Rewrite the function. After all it's no more than 10-20 lines. If it is longer rewrite the function anyways it's to long and that's part of why it's unreadable :) rinse-repeat

and in the unlikely case it's still unclear what the code is doing and you've remembered to ask your peers for help. Well then We all thank you for helping evolving Linux cuz it is kernel code you're writing right? if not rinse-repeat from the top :)

Simply put don't write you're comments CODE them

share

You would want to avoid writing comments just like you would want to avoid any documentation. When it comes to the programming language itself, everyone is operating from the same set of vocabulary and syntax (almost).

When your app is for a particular domain, it can be difficult to get everyone involved to agree on and/or establish a common vocabulary. We're taught to avoid abbreviations and extensive jargon, but I'm going to call it

EBITDA

and not

EquityBeforeInterestTaxesDepreciationAndAmortization

If you don't know one, you probably don't understand the other. If the company has some uncommon implementation, a comment would help the next programmer who may have experience in the domain, but not this particular firm (Which just makes things more complicated.).

share

Check out Code Complete 2nd edition, pg 128-129.

Abstract Data Types will save you from this conundrum. Self documenting code is the way to go. Comments can be useful, but having

real-world entities rather than low-level implementations

you're able to avoid using comments.

One thing about comments is that you write them once, but you don't see them when you implement the function, you only see them when you change the function.

Comments are really useful when they're interpreted by the IDE the way Delphi 2009+ or JavaDoc works, but that's more of a structured markup language, so in a sense you're programming your documentation, which is very smart.

share

Luckily, both camps on this discussion are represented here, and pro and con arguments for both were mentioned.

I believe both camps have overlapping arguments, and actually agree on most of them, just the way how to achieve them is a bit different.

Overlapping arguments

  • Code should be readable.
  • Comments shouldn't say the exact same thing as the code does, but give further insight where necessary.
  • All variable/function names should be given good thought so they give a good representation of what they are/do.
  • Duplicate code should be prevented.

Now, the main difference is how much weight is put on some of those arguments.

Self-describing code

  • Comments can get obsolete, so minimize using them, as wrong comments are worse than no comments.
  • Comments are a duplication of the code. Everything which can be written in code, should be written in code.

More comments

  • Comments are more readable than code. Plain english is better at describing something.

  • Plain code often causes ambiguity which has to be commented anyhow. Trying to describe this in code, results in too long names. Furthermore, you are constantly confronted with this 'extra' information which you only need the first time you come across it.

I believe both camps have very valid arguments, but you shouldn't frantically follow one camp, just because it solves one issue.

To demonstrate, in the book Clean Code, code is broken down into numerous smaller methods which are only called once. Methods are created for the sole reason to document the code (and easier TDD). This results in Function Hell. The code is less readable than it was originally, and while refactoring, no thought was given to encapsulate reusable code.

On the other hand, you often see API's where every function is commented, just because 'comments are good'. The things which should have been commented still aren't.

share
1  
+1 For consensus building and pragmatism! –  PeterAllenWebb Feb 25 '11 at 1:51

I think we need to distinguish between documentation and expressivity of the code.

When debugging or reviewing code, you're not reading a book. Most of the time you just want to jump from method to method and make quick connections in your mind to get a basic understanding of what's going on at runtime. It's not the documenting around the code but the expressivity of the code signatures that matters in that process, their ability to be meaningful enough that you can immediately identify them and add them to your own internal call stack. At that point, our brain (at least, mine works that way ;)) tends to consider large comment blocks as a noise rather than a help. Therefore, one-line comments, or even better, just self-descriptive method and object names are sufficient here.

If you want to "read the book" of a particular class or feature, a much better place for that is in the unit tests. Well-designed unit tests are by nature intention-revealing and much more documenting (ie explanatory, detailed) than the thickest of comment blocks since they contain 1/ the expectations on exactly what this code is supposed to do and 2/ the ability to check these expectations against the real code. A passing test is a hundred times more reliable than any comment in terms of documentation, because it proves that what it asserts is true.

share

Some code just is not self-documented, and requires some commentary from a fellow human who understood and tested that piece. What I have below just is not enough to understand it, I think.

//
// iterative version
//
Node* ReverseList( Node ** List ) 
{

  Node *temp1 = *List;
  Node * temp2 = NULL;
  Node * temp3 = NULL;

  while ( temp1 )
  {
    *List = temp1; //set the head to last node 
    temp2= temp1->pNext; // save the next ptr in temp2
    temp1->pNext = temp3; // change next to privous
    temp3 = temp1;
    temp1 = temp2;
  }

  return *List;
}
share

I generally favor writing self-documenting code, with comments where unclear, since I think most code will not completely document itself.

share

I believe in the mantra that code does not document itself, because you could be the best programmer in the world (Ada), and yet don't understand a thing about what is going on, but if you document why and in a short extent how your code is doing what it does, your going to help yourself and others in the future.

share

Comments are a must have. Because when you write code, you are writing for your current needs, but also for the people in the future who have to read your code, figure out wtf, are you doing, and why, and then how to make modifications for it.

If you just keep this in mind, when coding/programming?

How can i make this easier to understand and modify for future coders of this code I am working on, then you'll be doing a good job. Failing that, your just making it hard for others to modify your code, and don't imagine that never will be the case, that's rare...

At most of my job's, I have had always to modify other people's code, and most horribly written, poorly documented.

So your habit of thinking the code document it's self, is just not doing due diligence.

As programmer's we must practice the self-discipline that may appear to be totally a.r. to inexperienced programmers, but must have habits, to avoid all the horrible experiences we've had with other people's code. Or even looking at our own code months, years later.

Check out http://thedailywtf.com they have tons of humorous but real stories about programmer's who just didn't do their due diligence..

share

The Short, Better, and Correct Answer

The idea that well-written, "self-documented code" is all you need is an anti-pattern and should die, even when it makes exceptions for comments that explain "why". It's a myth that you can always write all code for any algorithm clear enough for any programmer to glance at and get it (or that it won't require refactoring or organizational time you don't have). Even more importantly, more often than not, programmers who think they write clear code do not.

A much better answer than comments should only be used to explain "why" is that comments should:

  • explain "why" (of course)
  • explain "what" on individual lines only when the code is complex or the purpose is unclear and it can't be or isn't worth simplifying further
  • explain "what" for blocks of code to speed up comprehension and locating what you need

The Explanation to Back It Up

People erroneously think the only reason people use comments is to explain what a line of code means. The truth is a large purpose of commenting code is to make it quicker to glance through your code and find what you're looking for. When I come back to code later or read someone else's code, sure, I can read and understand a section of well written code - but isn't it faster and easier to read the comment at the top saying what that section of code does and skip it altogether if it's not what I'm looking for? Why sit there and figure out code at all, even if it's well written, if you can glance at a couple comments and understand an entire function? That's why we use descriptive names for functions - no one says I don't need to use a descriptive name for my function because someone can just look through my cleanly written code to see what it does.

For example, if I'm looking through someone else's function, is it easier to go line by line through the code to see what it's doing or to glance at three well written comments throughout the function to see exactly what the function is doing and where it's doing it?

Another anti-pattern is the overuse of functions to comment your code. Well named functions are an important part of code documentation, but sometimes programmers separate 2-3 lines of code that will never be used anywhere else into a function for documentation purposes. Why is overusing functions any better than overusing comments? Using functions like that is the same as embracing GOTO statements - it creates spaghetti code that can be a pain to follow.

Essentially, when you work in an enterprise environment, where people are constantly sharing code and people don't always have the time to make their code perfect, a few good comments can save tons of time and frustration. And remember, while you may be a guru who can read through code at light speed, not everyone in your office probably is.

share
1  
I assume it's because you outright reject and name an antipattern something which is nearly universally recognized as right. I certainly think you go too far. Mostly, I can't imagine trusting comments as well as you seem to. If you blindly read the comments and not the code, the comments may be wrong and out of date, and you'd never know. That's the basis of using functions as documentation. I'll agree that you shouldn't have too many functions in one place, though the solution to that is definitely not to replace them with comments. –  Magus Feb 19 at 16:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.