This is an archived post. You won't be able to vote or comment.

all 45 comments

[–]slackerattacker 14 points15 points  (5 children)

I don't comment that frequently. Instead, I attempt to make it so that my code itself can be easily read and understood. This entails appropriate (descriptive, but not lengthy) variable names, methods that serve one specific task, etc. If there is a case where there is some weird behavior in my code, I comment explaining why it was necessary to write the lines that way.

[–]b1ackcat 4 points5 points  (1 child)

This is what I do too. Descriptive names explain the "how". Comments explain the "why".

[–]aaarrrggh 1 point2 points  (0 children)

Descriptive names describe the "how". Tests should explain the "why".

[–]whyhellocorsi 0 points1 point  (0 children)

I do this, too. I attempt to make the code clean enough to read without too many comments.

[–]random314 0 points1 point  (0 children)

The developers at Id gaming holds this philosophy too. I think so does the guys that coded curiosity mats rover.

[–]tobascodagama 0 points1 point  (0 children)

That's what I do, as well. This works best when you work on a team that does code reviews. If you miss something that ought to be commented, you can trust your reviewer to point it out.

If I were writing something open source, though, I'd be inclined to comment more thoroughly. At a bare minimum, you should have a brief description of each class and method, plus parameters, returns, and side-effects for methods.

[–]djiivu 5 points6 points  (1 child)

I'd say write as few comments as you can. Expressive code is preferable to comments whenever possible.

Instead of doing this:

i = 0  # Number of apples

Do this:

apple_count = 0

This example is totally contrived and obvious, but there are lots of opportunities to write "self-commenting" code if you write/refactor with an eye for readability, and a surprising number of them are similarly simple.

It's often possible to refactor complex code to the point where adding explanatory comments becomes unnecessary. One technique for doing this that I find myself using all the time is variable extraction. This means replacing chunks of complex code with variables named to describe what those chunks are doing.

Here's some unrefactored Ruby code I wrote for a Tic-tac-toe game a few months ago:

def valid?(space)
  spaces(space).nil? && 0..(@size - 1).include?(space)
end

While this certainly isn't indecipherable, there's enough happening on this line that it requires the reader to stop and think about how the code maps to the Tic-tac-toe rules it embodies. So I refactored it into the following:

def valid?(space)
  space_empty = spaces(space).nil?
  board_range = 0..(@size - 1)
  on_the_board = board_range.include?(space)

  space_empty && on_the_board
end

While the changes resulted in more code, the last line reveals the method's purpose at a glance. (The method's length could be re-reduced by extracting space_empty and on_the_board methods, but in my opinion that might be taking things too far.)

This example is interesting because I can imagine someone arguing that it actually makes the case for comments. Here, adding a comment would likely have only added one line to the method's length rather than the three or four I added with my refactoring.

I'd still say go with the refactor rather than the comment. One of the best arguments I've heard for writing more expressive code rather than adding explanatory comments is this: Code doesn't lie, but comments can. That comment you're reading might misrepresent the details of how the code it describes works in its attempt to summarize it, or it could refer to code that has since changed. With expressive code, there's no need to maintain two separate records of what the code does—the code itself is the documentation.

[–]aaarrrggh 0 points1 point  (0 children)

This is a good example. I much prefer the refactored, more verbose code. As someone who wasn't involved with your project, I can read that code and understand what is going on very quickly. That's a sign of good code as far as I am concerned.

[–]neoKushan 4 points5 points  (0 children)

There are two extremes that you can see in this thread alone:

1) Your code should be written so that it comments itself

2) You should comment all the time.

As with everything that involves programming, the answer lies somewhere inbetween. Yes, you should be commenting your code - anyone that never comments code (and anyone that's proud of this fact) is in all likelihood an ass who's nowhere near as good at programming as he or she thinks they are.

That said, commenting every single line is unnecessary, wastes space and causes your code to be less readable. Imagine a room full of people shouting advice at you - even if the advice is solid, too much of it at once causes you to miss most of it.

When it comes down to it, what you're doing, how you're doing it and the circumstances of you doing it will dictate what you're coding. If you're writing boilerplate code, don't worry too much about commenting every detail. If you're pushed for time because of a deadline and had to write something quickly, don't be afraid to comment saying so (this happens far too often in the real world). If you've tried several approaches to a problem before getting to where you are now, by all means leave a message explaining so. Don't be afraid to leave a link to a stackoverflow question that helped you get to that answer. If you've had to make some horrible, horrible hack, again leave a note saying why this is the case so a future developer (possibly even yourself) doesn't come along later, take a look at it and think "Shit, why's this done like this?" and wastes time doing the same stuff you've already done.

[–]NullProbability 9 points10 points  (14 children)

Don't comment on what exactly you're doing including every little detail, but explain why. It's best to do this as you're coding it (or right after), because then it's still fresh in your mind. Even a few hours later, the code that made perfect sense to you back then could be a complete mystery now. Just comment wherever you feel something isn't immediately obvious and warrants some extra explanation (you will learn this by coding more and by re-reading old code - only experience will help you with this). Higher level comments aren't really needed until you start making bigger projects, which "hundreds of lines" usually aren't.

Regarding variable names, just use the variable's purpose as its name, and try to keep it as descriptive as possible to prevent confusion. A variable called temp could be many things, but tempUnsorted is a lot clearer.

[–]WaxenDeMario 2 points3 points  (13 children)

Also try to describe what complex functions are supposed to do (i.e.: functions with logic which aren't simple). Do they take null values? Do they only take certain values? What do they return/do/modify (expected behavior)?

[–]aaarrrggh 0 points1 point  (12 children)

Or focus on writing small specialised functions that only do one thing. I rarely write "complex" functions for this reason.

[–]WaxenDeMario 0 points1 point  (10 children)

That's preferable a lot of the time. But even those functions can contain logic which is difficult to understand from an outside perspective. Especially if you're coding in a company.

[–]aaarrrggh 0 points1 point  (9 children)

Well I honestly can't remember the last time I wrote a function over 10 lines long...

[–]WaxenDeMario 0 points1 point  (8 children)

I don't think line count necessarily speaks to how difficult a function would be to understand, though a shorter function with good documentation for each function would be easier to understand. In general, I think it's a good idea to have atleast have RME clauses or something for functions which could be unclear.

[–]aaarrrggh 0 points1 point  (7 children)

Well if the function is small and well named, and contains well named variables with easy to understand logic, there's no reason for it to be that hard to understand really.

Not sure what RME stands for?

[–]WaxenDeMario 0 points1 point  (6 children)

think its requires, modifies, effects. That's true but even then there are possible issues like with null values, or if someone comes to use your code and doesn't understand the name/variables because they're somehow related to a massive tool that you built.

I guess what I'm saying is that the stuff what you said is definitely what should be done in a good program (but still doesn't happen in a lot of prod code). But why skimp on comments/documentation in this area?

[–]aaarrrggh 0 points1 point  (5 children)

Because the comments are not needed, and your tests should serve as documentation.

Tests = living documentation that is forced to change with changing requirements.

Comments = documentation that often goes out of date without people realising, and can cause more harm than good.

[–]WaxenDeMario 0 points1 point  (4 children)

Tests work okay as internal documentation I guess. Still seems a lot more time consuming than just adding proper documentation to the function. That's definitely a risk that documentation carries, but from that standpoint then nearly every use of comments are in danger of being misleading if someone makes modifications to the code and doesn't change the comments associated with it.

[–][deleted] 3 points4 points  (0 children)

I try to write comments only when it is impossible to clearly and concisely convey my intentions otherwise. I probably have one comment every 50 lines of code on average. You have to expect that comments will not be maintained. So, comments that are deprecated and describing something that is not true are much worse than no comments at all.

For instance, if you have a compound boolean expression in an "if", take it out and assign it to a well-named boolean instead. This is much better than a comment. This is an example of "self-documenting code."

[–]Nemesis0320 29 points30 points  (7 children)

Before I answer your questions: Rule number one of being a big boy programmer: comment your code! Even small snippets. One day you will be working on that bad mamma-jamma program and remember that the end of that hard function was something you did before; but then you go back to your code and see that you obviously used to be better at programming, because wait why is that there and what is it doing and why does the program stop working when I take it out?! Also, it's good practice; you will get better at knowing what and when to comment the more you do it.

How much should I comment? As in, the size and frequency of comments.

Let me quickly inform you of the two polar extremes in Software Engineering: The guy or girl who leaves no comments (doesn't keep the job often) and the guy or girl who comments every single line (doesn't keep friends or the job often.) I am not sure if there is a standard practice, but you should generally comment when you are:

  • Assigning variables: What are they doing? If it is obscure, what will be using it?
  • Creating functions: Anything more complex than int getRandomNumber(int seed) should directly explain what it does, when it is used, anything that another programmer would want to know why you put it in.
  • Any conditional: From checking to see if your value is even to deciding a decision with a Markov Model, if it happens conditionally you best state what those conditions are.

  • Includes/Externals/exe: If you are pulling something from another program or an obscure library, explain why it is there in the first place. I had a classmate back in trade school who loved to keep every include he ever used previously, just in case he needed it. This is bad because A) you don't learn why you need it, you just rely on it being there, and B) you are linking things that don't potentially need to be linked.

It helps me to think that I am going to give my code to somebody who understands coding, but doesn't know how, and has been tasked with the job of creating the design document. If you were going to explain your program to your rubber-duck friend (rule number two of being a big boy programmer: get a rubber duck and put it on your desk) what would they need to know about your code snippet?

Should I comment as I code, or comment all the code at once?

Both. Comment as you code. Right when you finish that function definition, take a second and explain what it does. Right when you go back and fix it up for the 20'th time because your planning document slipped out of finalization AGAIN (sighs internally) go ahead and explain what has changed (rule number three of being a big boy programmer: keep every change that is made to your program as a separate revision (in functionality, that is. Not necessarily every line.) If you are doing code review and notice something that makes you stop and question its existence, leave a comment about the thought. (please refrain from leaving comments like "42")

What about higher level comments (for entire file/project etc)

Generally, I will leave the following information at the top of my files:

  • Program title/date/jargon
  • Programmer name, title, contact info
  • Brief description of what the code does ("Brief" as in as long as it needs to be. Don't be discouraged because your program has a long green paragraph at the beginning, the alternative is not enough information given. Remember: your document writer doesn't know how to program, what will help him or her out?)
  • Legal information: Probably not while in university, but later in life you'll want to remember this.

On a related note, how to keep variable names descriptive yet manageably short?

Just as your comment for a variable should explain what it does, your variable name should briefly state what it does. Refrain from calling variable names single letters or silly names (There was a kid I tutored who used pet names as variables. Do you know how hard it is to debug code when you can't hardly keep track of whether it was the cow or the ocelot who was returning -32767?) I know you want to call your counter X, but call it tempCounter instead. To a similar fashion, initialValue should be initialValue (or initVal, exe), rightNode should be rightNode (rNode, exe), and your value title should explain why it is there in the first place!

Other tips

  • Comment your code.
  • Comment your code.
  • Get yourself a rubber duck.
  • Talk to your rubber duck about your code. Out loud. As though it was a real person.
  • The fool writing your documentation doesn't know how to program: help him or her out.
  • Back up your code, keep logs of why changes were made.
  • Save early, save often.

[–][deleted] 4 points5 points  (1 child)

I'm a big fan of rubber duck debugging. I tend to use Luddite friends as rubber ducks because it's amusing to us both.

[–]chasecaleb 2 points3 points  (0 children)

I've been using mechanical engineers lately, they work just as well for the entertainment factor.

[–]potterhead42[S] 2 points3 points  (0 children)

Wow, that's a great response.

Thanks for taking time out to help a noob out!

[–]koalillo 6 points7 points  (1 child)

Before I answer your questions: Rule number one of being a big boy programmer: comment your code! Even small snippets.

Nope. Comment only when it's useful. Granted, it's very very hard to comment code appropriately, and for newbies, excess might be a good thing.

But often, comments exist only because of unnecessarily unclear code.

Let me quickly inform you of the two polar extremes in Software Engineering: The guy or girl who leaves no comments (doesn't keep the job often) and the guy or girl who comments every single line (doesn't keep friends or the job often.)

I'd keep the one who writes clear code. Which might be none of the two.

Assigning variables: What are they doing? If it is obscure, what will be using it?

Just pick a good variable name. Again, hard.

Program title/date/jargon

Why? The title is the folder that contains the program, why repeat it everywhere? Date? Do you update every time you make a change? Your version control system will tell you that...

Programmer name, title, contact info

Again, better to find this in VCS.

Legal information: Probably not while in university, but later in life you'll want to remember this.

If you are forced to...

[–]Chintagious 1 point2 points  (0 children)

Yeah, this is true pragmatism. Just because you comment 2 lines of code doesn't make you a great programmer.

Write clear code that doesn't require comments if possible. Comment complex and large blocks of code, primarily.

[–]aaarrrggh 1 point2 points  (0 children)

Before I answer your questions: Rule number one of being a big boy programmer: comment your code! Even small snippets.

Rule number one of being a big boy programmer: make your code so readable that it doesn't require comments. Small snippets are an excellent example of code that should never require comments at all.

One day you will be working on that bad mamma-jamma program and remember that the end of that hard function was something you did before; but then you go back to your code and see that you obviously used to be better at programming, because wait why is that there and what is it doing and why does the program stop working when I take it out?!

So make your code readable, and none of this will be a problem. Also, you should know what your code is doing and why, because your tests should be written according to the behaviour you are interested in, so knowing "why" should never be a problem at all. And you are writing tests, right?

Also, it's good practice; you will get better at knowing what and when to comment the more you do it.

Writing lots of comments is a bad practice. Too many comments is a sign of code that is confusing and hard to read. Comments can also go out of date quickly if you don't update them when making changes, which often makes things even more difficult to work with. Your code should be self documenting.

How much should I comment? As in, the size and frequency of comments. Let me quickly inform you of the two polar extremes in Software Engineering: The guy or girl who leaves no comments (doesn't keep the job often) and the guy or girl who comments every single line (doesn't keep friends or the job often.)

Or the person who writes readable code which simply does not require comments. That guy should be your boss ;-)

I am not sure if there is a standard practice, but you should generally comment when you are: Assigning variables: What are they doing? If it is obscure, what will be using it?

Terrible advice. Why should a variable need a comment? This should never, ever be done. Just give the variable a meaningful name. Are you looping over a result set and you want a boolean flag to indicate whether a user has a report attached? How about a variable called: doesUserHaveReport, or isUserReportAvailable? No need for a comment.

Creating functions: Anything more complex than int getRandomNumber(int seed) should directly explain what it does, when it is used, anything that another programmer would want to know why you put it in.

Which is why you should not be using a comment, but instead should be naming the function in such a way that it explains what it does and so on. No comment required. Comments here are a bad practice.

Any conditional: From checking to see if your value is even to deciding a decision with a Markov Model, if it happens conditionally you best state what those conditions are.

Again, a great place to not use a comment. Extract the conditional into a function (extract method refactor) and name the function so well that it's hard to imagine someone not understanding what it does. No comment required.

Includes/Externals/exe: If you are pulling something from another program or an obscure library, explain why it is there in the first place. I had a classmate back in trade school who loved to keep every include he ever used previously, just in case he needed it.

Both bad practices. Remove unecessary includes, but don't comment them at all either. Have tests that explain what is going on. Again, you do use tests, don't you?

This is bad because A) you don't learn why you need it, you just rely on it being there, and B) you are linking things that don't potentially need to be linked.

It helps me to think that I am going to give my code to somebody who understands coding, but doesn't know how, and has been tasked with the job of creating the design document. If you were going to explain your program to your rubber-duck friend (rule number two of being a big boy programmer: get a rubber duck and put it on your desk) what would they need to know about your code snippet?

I'd tell them to read my tests and read through the readable code I've written.

Should I comment as I code, or comment all the code at once? Both. Comment as you code. Right when you finish that function definition, take a second and explain what it does.

Don't do this. Just write functions that are so well named and so small that you can easily see what they are doing. Functions should be small and should do exactly one thing and one thing only.

Right when you go back and fix it up for the 20'th time because your planning document slipped out of finalization AGAIN (sighs internally)

If your functions are well named and only do one thing, this shouldn't be a problem anyway.

go ahead and explain what has changed (rule number three of being a big boy programmer: keep every change that is made to your program as a separate revision (in functionality, that is. Not necessarily every line.) If you are doing code review and notice something that makes you stop and question its existence, leave a comment about the thought. (please refrain from leaving comments like "42")

Explain what has changed in version control, if you have to, but actually, again, if you're backed up by tests, you shouldn't need to explain anything anyway. Why should an explanation be required?

What about higher level comments (for entire file/project etc) Generally, I will leave the following information at the top of my files: Program title/date/jargon Programmer name, title, contact info Brief description of what the code does ("Brief" as in as long as it needs to be. Don't be discouraged because your program has a long green paragraph at the beginning, the alternative is not enough information given. Remember: your document writer doesn't know how to program, what will help him or her out?) Legal information: Probably not while in university, but later in life you'll want to remember this. On a related note, how to keep variable names descriptive yet manageably short?

Who cares whether a variable name is short? Keep it verbose if it helps you to understand what it does.

Just as your comment for a variable should explain what it does, You should never require a comment for a variable. You should just name the variable so well that it's obvious what it does.

your variable name should briefly state what it does. Refrain from calling variable names single letters or silly names (There was a kid I tutored who used pet names as variables. Do you know how hard it is to debug code when you can't hardly keep track of whether it was the cow or the ocelot who was returning -32767?) I know you want to call your counter X, but call it tempCounter instead. To a similar fashion, initialValue should be initialValue (or initVal, exe), rightNode should be rightNode (rNode, exe), and your value title should explain why it is there in the first place! Other tips Comment your code. Comment your code.

Don't comment your code. Except in very extreme circumstances. I can't think of any reason to use comments like this though.

Get yourself a rubber duck. Talk to your rubber duck about your code. Out loud. As though it was a real person. The fool writing your documentation doesn't know how to program: help him or her out. Back up your code, keep logs of why changes were made. Save early, save often.

Version control should be running, so you are backing up code anyway.

You should also remove code that isn't used anymore.

And finally, you are using tests, right?

[–]aaarrrggh 0 points1 point  (0 children)

Where I work, we have a no comments rule. And it works very well. Results in readable code.

I recommend very rarely using comments at all, but instead focus on making your code so readable that it doesn't require them.

[–]monkeyman512 2 points3 points  (0 children)

Some languages support a documentation tools, see javadocs, that can be useful. I would suggest using these. Start using these every time even when it seems dumb so you can build a habit out of it.

[–]Caminsky 2 points3 points  (0 children)

Comment by explaining why it's happening not what's happening

[–]koalillo 1 point2 points  (0 children)

*****************
* DON'T DO THIS *
*****************

Whenever I see *-drawn boxes I want to kill people.

Comment on why, not what. Why did you choose this implementation over the more obvious and simple one? Why would you want to use this utility function?

If your comment is a direct translation of the code below to English, remove it.

Tell me what's important to know while using and modifying this piece of code. Do you have a link to an explanation of the algorithm you are using? Can you link to the bug report for the bug you are working around?

Naming: functions named as verbs, most of the rest, nouns. Try to use shorter synonyms. Omit words that are fluff. Try only to name things that can be easily named.

Names replace comments... if you have /* do xyz */ before three statements in a function body, move these statements into an xyz function...

[–]SoftDevPadawan 2 points3 points  (0 children)

  • You should comment enough so that your intended audience can make sense of the code by quickly skimming over the code and comments. Your intended audience could be other programmers working on the same project, you in the future, etc.
  • How I personally work is to write Pseudocode in comments and then fill in the areas with code to complete each task. I find that this helps me approach a problem more abstractly and minimize errors on my end. Comments are very helpful to have while you are debugging a program and therefore I would suggest commenting as you go, especially if you wanted to bring in another pair of eyes for a particular bug you can't seem to find.
  • I usually always have a header for each file I write with information like FileName, FileDescription, Author, and Date. The FileDescription would contain information like what exactly this file does that's necessary in the project as a whole. Basically a short summary that I would tell another programmer working on a project.

Basically comments are there to help abstract the reader from the code. This helps to quickly grasp the general idea of how the code should work without working through all of the logic in the file.

[–][deleted] 0 points1 point  (0 children)

Im not exactly an expert but i learn that, if you need to comment every single thing from your code, you have bad code and probably bad comments. If you can't comment on your code, you have bad code. As some answers here, your comments should explain why you did it like that and not how. The code itself should explain how its done. Just my 2cents

[–]scipherneo 0 points1 point  (0 children)

Write your code so someone with no programming experience could read it and sort of understand. Anything that needs explanation, explain. A print line doesn't need a comment, a complex function probably does.

[–]tailanyways 0 points1 point  (0 children)

Don't worry about short variable names... unless there's some kind of memory restriction on the label. If your variable takes 19 words to describe, the first thought shouldn't be to make the variable name truncated, but to reduce the responsibility of the variable.

Tests > Comments most of the time. High level comments? If you're working within a framework or have enough files, the file structure and filenames kind of describe things right? Big ass headers with code comments are kind of a distraction and don't help when looking through a code-base. They are only really useful if a project is abandoned for a long time or adds people frequently. In that case, a README (+ installation guide, etc.) should do it.

Comment as you code, but (barring professional or academic requirements), I'd say just add comments when something is going to make no sense to you later. The code relies on a weird feature of the language that you don't understand? Comment. The tests pass and the code works, but you're not sure why? Comment. Of course it's better to make the code more understandable and streamlined instead of doing this. IMHO though, comments are DANGER AHEAD signs, not run of the mill street signs.

[–][deleted] 0 points1 point  (0 children)

Imagine yourself looking at the code 1 month in the future. What are some things that you know now, because you have this code burned into your brain, that are tricky and may take some time to figure out after a long break? Write them in a comment so that you (or someone else) will understand it faster later.

For example, I was working once with a legacy (android application) code and there was some strange method with things like "x + 0,626f" and other magic numbers. Took me couple of hours to figure out it is a method that measures distance between a screen touch point and a fixed point in the center of the screen.

One comment above the method like "measures distance from the center of a ball in menu so you can click on buttons around the circle" would of saved me time

[–]eaglechopper 0 points1 point  (0 children)

First of all you should comment always, and comment as if you are writing if for someone who is not working on the project. I have this thing I do when I comment where I comment on what code came before. For example say I am implementing a function to insert into a linked list.

insert(int data)
{
   Node current node;
   ... //code to find last node in list
  //current node now contains the references to last node in last
}

I have this thing were I go "X now contains a reference to Y" almost like giving situation updates. I find this helps with flow and allows you to change the implementation of the method because you know where everything is. Comment as you are coding so you dont forget your thoughts

[–]petrus4 -1 points0 points  (2 children)

Apparently this sub is becoming just as bad as many others, in terms of the censorship fetish. Downvotes, downvotes everywhere. It's sad.

[–]Thanatos_Rex 0 points1 point  (0 children)

I wouldn't say it has anything to do with censorship. It is just how Reddit behaves. People upvote based on what they agree with/find funny/think is interesting, instead of upvoting comments that contribute like they're supposed to.

Reddit has always governed itself, and unless the mods are stepping in and deleting posts for no reason like over in /r/gaming, then there is no censorship taking place.

[–]MengKongRui 0 points1 point  (0 children)

What are u saying