Self Documenting Code Vs. Commented Code

coding-standardscomments

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?

Best Answer

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.

Related Topic