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 am a young programmer (finished computer science university but still under a year of working in the industry) and I recently got a job working on some C code for a decent size web service. Looking at the code the only places I saw comments were when people were stashing their old code. Function and variable names are similarly informative most of the time - futex_up(&ws->g->conv_lock[conv->id%SPIN]);. Confronting a senior programmer about the situation and explaining that adding comments and meaningful names would make the code more maintainable and readable in the future, I got this reply:

In general, I hate comments. Most of them time, like the case you mention with the return value, people use comments to get around reading the code. The comments don't say anything other than what the guy thought the code does at the time he put in the comment (which is often prior to his last edit). If you put in comments, people won't read the code as much. Then bugs don't get caught, and people don't understand the quirks, bottlenecks, etc. of the system. That's provided the comments are actually updated with code changes, which is of course totally unguaranteed.

I want to force people to read the code. I hate debuggers for a similar reason. They are too convenient and allow you to step through dirty code with watches and breakpoints and find the so-called problem, when the real problem was that there are bugs in the code because the code has not been simplified enough. If we didn't have the debugger, we would refuse to read ugly code and say, I have to clean this up just so I can see what it is doing. By the time you are done cleaning up, half the time the bug just goes away.

While what he wrote goes against a lot I have been taught in the university, it does make some sense. However, since experience in the studies sometimes doesn't work in real life, I would like to get an opinion of people more vetted in code.

Is the approach of avoiding commenting code to make people actually read the code and understand what is going on make sense in a medium-sized coding environment (one that can be reasonably read in whole by every person working on it within a month or two), or is it a recipe for a long-term disaster? What are the advantages and disadvantages of the approach?

share|improve this question
Anybody who says he hates debuggers has never had to find/fix a hardware bug. –  Carl Norum Jun 15 '13 at 17:02
He hates comments and debuggers (a.k.a. he doesn't use them) and he calls himself a senior developer ? You still call him that ? No offense, but he should really pick up some books/articles about programming best practices from the 21st century. To be more specific: if the code is self-explanatory, then comments are indeed not needed. But when they are, you should put as many comments as necessary. –  Radu Murzea Jun 15 '13 at 21:18
Linus Torvalds has some strong opinions on debuggers ( "Without a debugger, you basically have to go the next step: understand what the program does."): lwn.net/2000/0914/a/lt-debugger.php3 –  timday Jun 15 '13 at 22:00
"I saw comments were when people were stashing their old code." is another red flag. That's supposed to be what the version control system is for. –  user16764 Jun 15 '13 at 22:30
As a junior programmer I hated code without comments; as a senior developer I find code with too many comments is probably badly written. Rewrite the code until it doesn’t need comments. If after attempts to simplify the code it still need comments, then the comments are probably well-justified. There is no excuse for badly named variables or classes however. Name things well people. –  mxcl Jun 15 '13 at 23:48
show 17 more comments

marked as duplicate by gnat, GlenH7, Kilian Foth, Bart van Ingen Schenau, Martijn Pieters Jun 17 '13 at 10:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

19 Answers

up vote 84 down vote accepted

Well written code should be sufficiently self-documenting that you don't need any comments explaining what the code does, because it is obvious from reading the code itself. This implies also that all functions and variables have descriptive names, although it might be needed to learn the lingo of the problem and solution domains.

This does not mean that well-written code should be completely without comments, because the important comments are those explaining why a particular, non-trivial, function/block/etc is implemented as it is and why not a different solution has been chosen.

The problem with comments describing the code itself is that they tend to get outdated, because the code gets changed to fix a bug, but the comments remain untouched. This is far less the case with comments describing the reasoning for coming to the current solution.

share|improve this answer
+1 - I'd like to add that this is a fairly universal best-practice these days. –  Telastyn Jun 15 '13 at 16:31
+1 For comments not explaining what but why. –  Benjamin Gruenbaum Jun 15 '13 at 21:26
+1 design choices are commented –  Fuhrmanator Jun 15 '13 at 21:52
Now define well written code :) –  Chris S Jun 16 '13 at 13:19
show 3 more comments

Someone (attributed to Richard C. Haven, a Delphi programmer) once wrote:

  • Beginners comment nothing.

  • Journeymen comment the obvious.

    myVar = myVar + 1; // add one to myVar
    /* This method adjusts the page margin by the appropriate device offset */
  • Masters comment the reason for not doing it another way

    I already tried obvious approaches A, B, and C to solve this problem.
    They didn't work for the following reasons: ...
    Therefore I wrote this less-than-obvious approach which works and 
    passes all unit tests.  

Your "senior programmer" may be senior in terms of age / longevity, but it sounds to me like he has some professional growing up to do.

As for debugging, there's a lot to be said for clean code and liberal use of logging and/or print() statements. However, using a good debugger I can usually find the problem in a tiny fraction of the time it would take without it. It's a power tool. Use it.

share|improve this answer
Comments at the tops of methods are good practice regardless of the experience level, as they can get picked up by automatic documentation tools for people who only need to understand your code's API, not its internals. –  Amy Blankenship Jun 15 '13 at 20:45
add comment

I want to force people to read the code. I hate debuggers for a similar reason. They are too convenient and allow you to step through dirty code with watches and breakpoints and find the so-called problem, when the real problem was that there are bugs in the code because the code has not been simplified enough.

Your senior programmer seems to have an understandable problem about coding style. He's wrong in how he tackles the problem, though.

Both comments and descriptive coding are essential: well-written code with descriptive names quickly tells you what code does; but the comments tell you what the code should do (and why not, why it does it one way and not another. Then you have unit tests to verify that the "contract" (what the code should have done) is actually fulfilled, and do it automatically, frequently and with no further effort on your part.

Without the comments, it would take a long time (or a unit test, which at this point I suspect your boss likes even less than comments, if he believes that "bugs get caught by people reading code) before finding the error:

// Multiply margin by a fixed amount.
page->margin += fixedMargin;

and, yes, the comment might be wrong, but now you know that in one of those two lines there's an error. This, plus another useful resource, version control, enables you to find the discrepancy in less than 30 seconds. Verifying the output and even stepping with a debugger might not (a value of fixedMargin of about 1.01 could give you ambiguous results, for example).

If your mentor is after simplicity (I agree with him that it's a desirable trait), he ought to deploy some way of checking metrics such as cyclomatic complexity and establishing metric goals. That goes for comments too: I agree that it makes no sense to document every single line of code, but you should strive to cover modules, functions and any "WTF point" in the code.

// Useless comment: multiply a by four

// Useful comment (even if maybe it shouldn't be in this exact point of code):
// Zooming 2:1, four pixels get mapped into one, divisor needs multiplying by four
a *= 4;

His method may give results - in the case he hates, you would have 20% coding and 80% documenting and testing. With his method you get 20% coding and 80% debugging and head-scratching.

The difference between the two cases are, I think, in people's morale and in overall productivity. If you properly document and mock functions and modules, a module can be implemented by someone who does not need to know the overall picture, does not have to study side-effects in a black box scenario, and for bottom line's sake, can be less experienced.

Your mentor is apparently comfortable running up a fearsome amount of technical debt. I'd check his stats on deadline slippage and/or ETAs; short of a miracle, any long-running project not kept up by a one-man-band or a tightly knit group of coding buddies is due to have its technical debt called in sooner or later.

share|improve this answer
A unit test does a far better job than a comment of telling you that there is a bug somewhere between the two lines of code. –  Telastyn Jun 15 '13 at 16:32
@Telastyn Unless the test is also wrong. –  Izkata Jun 16 '13 at 5:52
@Izkata - indeed, but if the code and test were wrong, what's the odds the code and comment are both wrong? Just as good if not better. If the code and test differ, you know immediately. If the code and comment differ, you might notice if someone finds the bug. –  Telastyn Jun 16 '13 at 13:16
show 1 more comment

If you can only "read the code", you will not get an idea of what the function is intended to do. So, if someone fucks up (I know nobody does, this is a hypotetical case) and do something wrong, you have no way of checking it in the code. You have to wait for unit tests to detect it (if they check it).

Add to that, that not adding comments forces me to read functions A1, A2, A3... from beginning to end while I am only interested in understanding function A, which calls all of the above.

I would bet on your senior programmer being lazy (bad) or wanting people to notice how cleverly he codes (way worse).

share|improve this answer
@markijbema I would be willing to wager that if all function/method names explained their intended. That the length of those names would be about the same length as the comments for that function/method. –  Mathew Foscarini Jun 16 '13 at 16:07
show 2 more comments

Comments should be used as a written record which explains something confusing. If you're writing something that is potentially confusing and cannot be simplified, such that you suspect that even you will have a hard time understanding it six months later, then write a comment.

If you comment liberally, everything and everywhere, then comments lose their effectiveness at flagging the difficulties. (Rememer the fable of the boy who cried "Wolf!")

Comments occupy "screen real estate", unless you have a good folding editor; you have to keep skipping past them when moving around in the code. And of course comments like /* increment i by one */ next to i++ are complete garbage.

If the code is so complicated that it requires a guide to the internals, then, by golly, write a guide to the internals. Call it README-internals.txt (or perhaps HTML) and stash it in the same directory as the code, and put in a comment which says /* this is all explained in README-internals.txt */.

About debuggers: any tool which helps you find a bug is valuable. It is silly to dismiss tools. Breakpoint debuggers should not be used to verify that code is working. At least, not relied upon as a primary means. A debugger will cheerfully step over a statement like a[i] = i++ in C and confirm a bad intuition.

Debugging tools which actually catch some kind of run-time violation, however, can be relied upon as a test tool. If you have a debugger that catches misuses of dynamic memory, and the code passes numerous test cases under that debugger, that is a source of confidence that memory isn't being misused.

So, keep in mind that "debugger" refers to more than one kind of tool, not only a breakpoint/step debugger. Some debuggers only provide a view into the program, leaving you to do the reasoning about what is wrong, whereas other debuggers look for problems for you.

Code cannot always be simplified for the sake of not having a debugger or refusing to use one. What if you follow your boss' suggestion and simplify the code to the point that it cannot be simplified any further, and you still need a debugger?

share|improve this answer
add comment

If you put in comments, people won't read the code as much. Then bugs don't get caught, and people don't understand the quirks, bottlenecks, etc. of the system. That's provided the comments are actually updated with code changes, which is of course totally unguaranteed.

Nothing like an opinionated idiot.

Next time when you are shopping for a book to read. Besure to read it cover to cover before you buy it. Otherwise you'll never know exactly if it's what you were looking to buy. That's basically what he's telling you to do.

He has made a few assumptions that are foolish.

  1. Reading the source code will provide you with the purist perspective of what it does.
  2. Comments pertain to the scope of the source code they are associated with.

That is his narrow perspective about comments, and as such he sees no value in them. Here are the limitations of not having comments.

  1. Source code is an instruction set for a computer. It does not expression concepts or ideas. Therefore, source code will never tell you what the programmers objectives were. Source code that compiles without errors and does not crash can still fail to meet the objectives. How will you know any different from the computer by reading the source code? The computer already does that, yet it could still fail to meet the objective.
  2. Source code does not explain the programmer's intent. open window, prompt for deposit does not explain that the programmer intended to communicate a warning to the user.

Next time you have a conversation with this guy and he asks why you are adding comments to your source code. Reply with this statement.

"I write source code to tell the computer what to do, and I write comments to tell people what to do."

share|improve this answer
@Telastyn so you read the answer, misunderstood and found clarity in the comments. How ironic :) –  Mathew Foscarini Jun 16 '13 at 15:55
show 3 more comments

I find that code review is a fantastic process for answering this question in concrete ways. If I read someone's pull request (putting forth actual effort to read it, not just glancing at it with the attitude that everything must be immediately apparent) and can't understand what it does, I tell people to add a comment. Or you can do this by yourself with a rubber duck.

Most people inuititively know what ideas needs to be commented - It's whatever you would say to someone standing next to you if they asked you a question about the code. Often I'll ask someone to explain something in a review, they'll give a great answer, and my response is "Copy that explanation you just wrote into a comment in the code."

But for some reason that's rarely the content that people end up writing in their comments. Instead people write inane stuff like

 * Gets the {@link List} of {@link Author}s for the given {@link Book}.
 * @param book The {@link Book} for which you want the {@link Author}s.
 * @return All of the {@link Author}s for the given {@link Book}.
List<Author> getAuthors(Book book) { ...


// increment i by 1
i += 1

and that's the kind of stuff that the experienced coworkers are reacting to. I myself tell people when I'm reviewing code to remove these sorts of low-level comments that add no more information than can be found in the immediately surrounding lines.

One prime example of a trivial thing that does need to be commented is descriptions of duck types in dynamic languages. If a function's argument or return value is a dict with a bunch of properties on it, you're in for some insanity later on if you don't comment exactly what those properties are.

No amount of commenting will raise any nontrivial code to the level that an 8-year-old could understand, so you shouldn't try. You have to make some assumptions that the reader knows how to read the code, because otherwise it's a completely futile effort.

Finally, comments are very often wrong. People often skip over them when reading, and don't update them when things change. You can't write a unit test for your comments, so only the way to defend your code against the rot that occurs when your careless coworkers start monkeying with it is to comment only the ideas are are essential. Comments that don't add value add negative value when they become erroneous.

Document design, ideas, architecture, history, rationale - not lines of code.

share|improve this answer
add comment

In a perfect world without deadlines his approach might work.

A user reported a bug in application X. We'll let the new guy spend two months to get a deep and thorough understanding of the code, and then maybe add a few weeks of refactoring. If the bug still occurs, he should be able to find it then and won't even need a debugger!

In the real world, this sounds like a reliable way to get out of business.

share|improve this answer
@AndresF. - being a pro means being able to write decent code and meet the deadline (more or less). I say decent, not great or perfect: The 'real world' is about compromises, and this is where a good relationship between technical staff and business people is CRITICAL. –  comeAndGo Jun 16 '13 at 1:08
show 5 more comments

Example of bad comment

foo(); //calling function foo

Good comment

foo(); // must call function foo, because of a bug {link to bug}
share|improve this answer
show 3 more comments

Code Complete, the seminal work on coding style, devotes several sections (starting with 19.3 in edition 1) to the question of comments: the good, the bad and the ugly. So you, and your senior developer, should probably take a look there.

Having said that, well written and well placed comments are very important IMO, for any large scale/long-term project.

In a perfect world, it's true that comments would not be important. But unless you have a photographic memory and everyone who works on your code is a genius, good comments just help to understand the code that much quicker when you have to go back to it a year or two later and modify it, or someone else inherits your code. (I'm saying this having worked professionally for 20 years, and as many as 5 or 7 years on one project with several other developers involved)

A few years ago I inherited a complex application that gets the job done but suffers from poor architecture and an inconsistent, bloated coding style. Luckily, the code is fairly well commented, which saved me days and weeks of getting up to speed with that code base.

Another thing that helped me get up to speed was the debugger I use. When I go to analyze a new piece of software that I have to work on, one of the first things I do is go through all the menus, make invalid or weird selections and see if I can break the app. When I do break it, I run that scenario with the debugger and see where that failure leads me. Almost invariably this leads me to important modules and junctures in the code base: A quick way to find the important places on the map.

Although with my own code I generally don't have to use the debugger very much, there are occasions where it does help - nobody is perfect, even if they are meticulous about unit testing (Which is often impossible when you've inherited tightly coupled legacy code.) And if I use a new module or component, the debugger helps me find quickly the errors and misunderstandings I have to deal with to help me get up to speed with the new stuff.

In short: Time is money, and most of us program to deliver products and pay the bills. Sitting for weeks on end going through hundreds of lines of code to find a bug the debugger would reveal in 10 seconds, or poorly written code that might be illuminated by some good comments, won't help your bottom line very much....

Your senior developer apparently is not concerned with efficiency and would prefer to have developers spend hours and days messing with complex code, when a few comments would save the day. Same goes for his ideas about debugging. (Just curious: does the senior developer use an IDE? Why not just type everything out in a text file and do a compile and link from the command line, etc? What better way to understand every single line of code...)

share|improve this answer
add comment

The comments don't say anything other than what the guy thought the code does at the time he put in the comment

You know, it's an extremely theoretical approach. I wouldn't surprised, if it was said by theoretical mathematician, but in sounds of senior developer it doesn't sound as if it was someone with really long practice.

Well, theoretically you can analyse the code in head, but it works only with very simple programs. With more complex, real-life ones you come across Halting problem, which is one of the most complex problems in computation theory. If someone says he can analyse programs in head, he can probably do RSA decryption in memory :)

It seems as either your senior developer has no real-life experience with complex problems, or is trying to impress you with tricks as taken from Hackers movie, or he want to justify his own laziness when it goes to writing comments.

share|improve this answer
add comment

Comments are for who, when, why, assumptions, dependancies, and possibly how.

Who wrote this? Who do I go and bug if I have questions about it?

When did they write it?

Why did they write it? What was the business reason that they spent time writing code?

Why did they pick this approach and what other approaches did they reject, and why?

What assumptions did they make? What beliefs about the organisation did they hold?

What things are required to happen for this code to execute successfully? What libraries, objects, environments or other things is it dependent on?

What are the situations in which the code might fail and how does the code deal with those failures? How do I deal with them?

As for the "how", comments should only explain how the code works if it is complicated and hard to understand (and if it is then perhaps the programmer should have put more effort into simplifying it).

share|improve this answer
show 1 more comment

What your senior developer is referring to is code entropy. I imagine he's referring to cases where code is badly designed, and the only way to understand it well and work with it are comments and debugger.

In other words, comments and debuggers can be used to work around underlying issues. However, they are both tools, and blaming the tool is not an effective way to go about anything.

For your example, if a codebase has a lot of broken code, then the solution is not to leave out comments and make everyone read as much code as possible. In fact, this is a waste of time and resources. Instead, set up processes like peer review and pair programming, where code written by one person is sure to have been reviewed by another. These processes not only achieve the same goal with better accuracy, they also avoid a waste of resources where dozens of developers have to understand one complex bit of code, just because it lacks comments and documentation.

Furthermore, efficient comments can actually reduce the amount of error in code. Reading them makes source code easier to understand, and often saves you from having to search through whole batches of source files, just to find out why a line of code is necessary. Sure, the comment may turn out to be wrong - But unless the overall quality of the project is downright horrible, you'll end up saving more time by trusting accurate comments, than you will lose to those that are outdated. And saved time on understanding, means more time for refactoring, which is a much better way to combat code entropy.

share|improve this answer
add comment

I'm writing code for about 30 years and I may have said something very similar to what said that senior programmer. I'm also very aware of maintenance problems.

Still I believe some very important points were forgotten in the above answers:

I have unit tests for most of my code. Don't you ?

The why of the functions (the intent behind the code) is usually expressed through tests and if tests by themselves are not enough they are commented, sometimes very heavily (if some of you heard of litterate programming they may understand what i'm speaking about).

On the opposite comments in my code are very sparse, nearly nonexistent, except for two special cases: - if what is implemented if following some normative references (like implementations of network protocols, what I'm currently working on) I usually put the reference as comment above the code. - I also use comments to avoid breaking programming flow. I insert comments like: this or that look wrong, fix it later when I'm coding some unrelated feature. These are short term comments (like programmer defined warnings) and should be fixed later.

My rationale on doing that is that comments in code can be misleading. You can easily read a comment and believe the code is performing what the comment pretends, even if it's not true.

When comments about code are in tests, things are different. It explains how code should be called and the test ensure it is actually doing that.

I usually not much use debuggers. I keep them for some special cases (mostly when I do not understand what the code does, like strange hardware bugs).

That changed with time. 30 years ago I heavily used debuggers. What I've observed is that finding bugs is usually much slower that other methods. What I usually do now is pinpoint bugs in unit tests, the earlier the better. That has the additional advantage to give a non regression test. Never bitten twice by the same bug.

share|improve this answer
What happens when you inherit a large code base that doesn't have unit tests? Comments have always been around - TDD, not. Comments are more for the next developer than for you. And unit tests do not help for complex logical problems when dealing with disparate modules that span different languages, time frames, data types and business rules. Skillful use of debuggers with all their bells and whistles becomes very important in such cases. –  comeAndGo Jun 16 '13 at 3:52
But basically I said it : debuggers are for when you do not understand the code you are working on. –  kriss Jun 16 '13 at 11:04
@Mikey: yes, of course Unit Tests are just another tool, like debuggers. –  kriss Jun 17 '13 at 7:46
show 2 more comments

I used to comment a lot, now very little, making the code and variable names readable is the way to go.
I add comments for real 'gotchas' and 'why this was done that isn't (yet) obvious from the code'.

But to your REAL question.

I note that your title starts with the word: "forcing"

I also note that the first paragraph mentions "confronting"

I used the exact same words 20 years ago myself :)

This (IMHO of course) is what programming is really about - how different people with different styles, opinions, experience, knowledge and background can work together.

There is no simple fix, no list of programmatic steps to take, no single conversation to set things right. I would recommend that you think over the following points that I have learned from my experience of 20 years.

  1. Listen
  2. Listen
  3. Listen. Sorry to make it such a big deal but nothing will help you more in your career now than asking questions and listening even if the answer don't make sense.
  4. Ask question and just listen to the answers even if you disagree or don't fully understand them. There is nearly always a second chance to revisit things.
  5. Accept that wring things get done sometimes. If they are really bad decisions that will continue to show and one can make a case later to make them better. But emphasis on the later. Good enough for now is something you have to accept sometimes so you can more on for now.
  6. Pick your battles on things that are wrong. Learn to hold your tongue unless the item is really really important to you and even then pick your battles very carefully - and try to make then conversations and not battles!
  7. Accept differences. Outside of academia you will need to accept more differences and focus a (little) less on finding the 'correct and true' way to do things and more on what works for today and for the business you are workgin in.
  8. Avoid black and white conversations. Don't be absolutist about the 'right thing' avoid words that are absolutist like 'must', 'only', 'impossible', etc. and use words like 'should' 'often' and 'hard'.
  9. Use concrete examples in conversation rather than theory. Don't avoid theory but in conversations try to have real examples for your points. If you don't have real world examples yet this may be a indicator that you should listed more than talk.
  10. Emphasize your youth and ignorance in conversations with more experienced programmers such as the one you mention. You will impress them more with humbleness than boasting about your recently gained knowledge.
share|improve this answer
show 1 more comment

Comments are very overrated and most frequently misused. Though I don't know about your current situation (since I don't find the quoted quote speaking for good code readability), in general you shouldn't spray comments all over your code (with perhaps the exception of highlevel comments, which are already close to documentation0.

It's for a reason that commenting is one of the code smells described in Martin Fowlers Refactoring book (for a summary, see: http://www.industriallogic.com/wp-content/uploads/2005/09/smellstorefactorings.pdf, the book is not freely available afaik).

However, you should substitute comments with meaningful method and variable names, and I don't think w and gs classify. However, personally I would press more on good naming, than on commenting.

Btw, if you search for 'clean code' and 'comments' or 'code smell' and 'comments' you find great reads about this, ie. http://franksworld.com/blog/archive/2010/07/01/12035.aspx (with a summary of why Uncle Bob Martin of Clean Code dislikes comments)

share|improve this answer
add comment

Any time you write code, you should be thinking about the next programmer who will inherit what you wrote. If you write comments because you were taught to do so as a best practice or just out of habit, you should probably stop writing comments all the time because anybody reading your stuff will start to ignore them as useless.

If you only comment when naming conventions and structure can't explain some weird element of what you're doing (usually because of something else in a codebase that's completely batshit), they'll pick up on that. If you're marking problematic bits of code, for crying out loud put a date on it so it's easier to review changes that led to the shenanigans in source control.

On the subject of debuggers, I can feel a twinge of solidarity on the (I'm guessing) old-school, primarily procedural guy because I come from JavaScript starting back when all IE told you was "Object not found." Why they even bothered, I don't know but when you occasionally have to deal with that sort of thing, you think a lot harder about how to structure your code in such a way that it's going to be a lot more obvious where something went wrong so you can rapidly diagnose with logging/alerts.

That said, I wouldn't trade Chrome Dev tools or Firebug for anything short of a Time-Travelling police box. But the point, I think, is this. If the first thing you do is start a trace in the debugger without even looking at the code that's involved, you may not be structuring your code as well as you could. Always strive to be as direct and obvious and minimalist and easy to read as if there were no IDE or debugger to help you. Start by looking at your code when you hit a snag first. If it's not easy to even guess where things are going wrong, you may want to put some more thought into how you'd go about writing code without modern tools. Most of the Java and C# I've ever seen is clueless about the basic fundamentals of OOP.

share|improve this answer
add comment

Comments are very useful, and can be the difference between clear code, and unclear code.

Just because it was done one way "back in the day" doesn't mean another way is unacceptable.

share|improve this answer
add comment

Comments in code are a Godsend when used correctly but as others here have pointed out they are often overused. I'm not going to re-iterate what has already been pointed out but I will say that you should only comment if you know that the code you are writing is complicated and there is no other viable way.

If you feel you have to comment, think about the code first and ask yourself; Why are you writing that comment? Is there another way of writing the code which wouldn't need a comment?

Don't write comments for the sake of writing comments. Comment only as a last resort or where it will help those who are going to have to work on the code further down the line. If you find yourself writing comments describing what a variable is doing then the chances are you're over-commenting. Bad programmers comment everything, good programmers comment only when necessary.

On the subject of debuggers, I work with some engineers who have gone their whole career without ever firing up a debugger. Why? A debugger is a tool like any other. Just like in most instances a ball-peen hammer will do the job, sometimes you need something with more finesse.

A debugger serves two purposes.

  1. It is used for finding bugs
  2. It shows a path through your code.

They can be very useful in bringing newcomers up to speed and they can be even more useful in tracing those very hard to find bugs but they are not the only way and there are times when a debugger is actually a hinderance more than a help.

As for function summary, well every function should have a docblock, this is a must but don't go making them long and elaborate. The summery should be a 1 line description with each parameter being clearly described.

 * A getter method for foo
 * @param bool $bar If true, bar will be attached to foo
 * @return foo

Only use a detailed docblock if there is cause to. If the method is over complicated then yes, put in an explanation but where possible, try and avoid it. Good code should document itself.

Remember, everybody enjoys reading novels but nobody wants to read war and peace at 9am on a Monday morning.

share|improve this answer
show 1 more comment

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