Is code commenting bad?

Page 2 - Seeking answers? Join the AnandTech community: where nearly half-a-million members share solutions and discuss the latest tech.

uOpt

Golden Member
Oct 19, 2004
1,628
0
0
If you just invented a new algorithm you should explain it in clear text, not have people figure it out from the code. Chances are your implementation isn't quite correct or complete so the latter is a losing proposition.

You should also have a basic overview of where and how program state is being held. I don't see how that's possible without comments.

If you use a standard algorithm but implemented it yourself you should say so. Chances are your implementation isn't correct anyway and it might not be easily recognizable.

The most valuable comments are of this kind "DO NOT TOUCH THIS UNLESS YOU KNOW WHAT YOU ARE DOING".
 

ObscureCaucasian

Diamond Member
Jul 23, 2006
3,934
0
0
I put most of my documentation at the function level (like doxygen/javadoc), however I will add some small comments at tricky parts of code. If you have lots of comments in function bodies then your functions are probably too large.
 

dwell

pics?
Oct 9, 1999
5,189
2
0
Code:
/////////////////////////////////////////////////
//
// Constructor
//
/////////////////////////////////////////////////

public SomeClass() 
{
}

^^^ I knew some guy who always did that. We had this 60 something year old, highly opinionated developer who would "refactor" that guy's code when he went home at night (meaning delete all that crap). He used to go around saying, "If you need five lines of code to tell you it's a constructor you have no business programming. NO business"
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
13
81
www.markbetz.net
Code:
/////////////////////////////////////////////////
//
// Constructor
//
/////////////////////////////////////////////////

public SomeClass() 
{
}

^^^ I knew some guy who always did that. We had this 60 something year old, highly opinionated developer who would "refactor" that guy's code when he went home at night (meaning delete all that crap). He used to go around saying, "If you need five lines of code to tell you it's a constructor you have no business programming. NO business"

Haha, that's awesome. He probably saw that in a "Learn C++" book and thought that's how it was always done.
 

cytg111

Lifer
Mar 17, 2008
23,548
13,115
136
descriptive variables, method names, commenting so on and so forth is all good and fine, use common sense, not rocket science.

If you really wanna make your code maintainable? You unit test, you unit test tf out of it, and if you dont allready have an automated buildserver running those tests, then get one.
While unittests take some time to develop, they pay them selves back many times, especially when you tincker with that code in the middle that may break stuff left and right if not done just right.
 

Stuxnet

Diamond Member
Jun 16, 2005
8,403
1
0
Code:
// Querying the account information to determine if the account has an email flag required to send out a notice.
Account->GetAccountInformation()

Ok, thats why we are gathering the account information. Good comment.

Not really. Since we declare variables when we need them, the next line of code that follows ought to be checking said email flag, which explains perfectly why Account is being initialized.

descriptive variables, method names, commenting so on and so forth is all good and fine, use common sense, not rocket science.

If you really wanna make your code maintainable? You unit test, you unit test tf out of it, and if you dont allready have an automated buildserver running those tests, then get one.
While unittests take some time to develop, they pay them selves back many times, especially when you tincker with that code in the middle that may break stuff left and right if not done just right.

Highly testable / mockable code does tend to lead to self-documenting code, compact code, etc.
 

brandonb

Diamond Member
Oct 17, 2006
3,731
2
0
Not really. Since we declare variables when we need them, the next line of code that follows ought to be checking said email flag, which explains perfectly why Account is being initialized.

Unfortunately in the real world, things may not be so clear:

(vb.net code)

Code:
                Dim objl_DISPOSITIONFLAG As ObjectModel.clsDefClientDispositionTypeFlag
                objl_DISPOSITIONFLAG = objg_CACHE.DefClientDispositionTypeFlags_UidDefClient_UidDefClientDispositionType_UidDefFlag(Connection, objl_MAPACCOUNTCALLS.UidDefClient, objl_MAPACCOUNTCALLS.UidDefClientDispositionType, 32)

                If objl_DISPOSITIONFLAG IsNot Nothing AndAlso objl_DISPOSITIONFLAG.Flag = True Then
                    MessageBox.Show(objg_LANGUAGE.CurrentLanguage(571).Description, strg_TITLE, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.None)
                    Return False
                End If

The flag is driven by a integer in a database table (on the disposition), and the message box/error box is also database driven by an integer, so without looking up what those are in the database to figure out the values, it's not going to be clear.

So you can look at the comment above it:

Code:
        ' We must have a payment plan

Now we can tell what flag type = 32 is related to, and what error message 571 is...
 

Stuxnet

Diamond Member
Jun 16, 2005
8,403
1
0
Unfortunately in the real world, things may not be so clear...

Well sure, in the example you just provided commenting is absolutely necessary. But I wasn't commenting (hehe) on that scenario, I was commenting on the other one, where it wouldn't be necessary at all.
 

Pia

Golden Member
Feb 28, 2008
1,563
0
0
Also, when editing another's code, or editing your code to try something - always add a comment with the date and what you changed.
This raises the hairs at the back of my neck. Don't you use version control? Are your incomplete changes randomly pushed to other developers, or releases?
 

BoberFett

Lifer
Oct 9, 1999
37,563
9
81
This raises the hairs at the back of my neck. Don't you use version control? Are your incomplete changes randomly pushed to other developers, or releases?

Version control is not a replacement for comments. Version control systems come and go. Comments stay with the code no matter it goes.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,284
3,905
75
Version control is not a replacement for comments. Version control systems come and go. Comments stay with the code no matter it goes.

In the past, you were right: version control systems held everything at a single site. But with modern distributed version control systems like Git, especially those that are open-source, the entire repository can go anywhere. So I'd say version control for commenting on versions is very much a good alternative these days.

Edit: P.S. If I ever do leave Git, I can dump the entire version history into a file or a set of comments first.
 

skrewler2

Senior member
Aug 28, 2005
279
0
76
<snip>
Also, when editing another's code, or editing your code to try something - always add a comment with the date and what you changed. Do not ever just comment out code because you will inevitably leave it like that if the change works.

What? That's what commit messages are for.


EDIT: Oops, I now see many others got irked by this post already.. carry on, don't mind me.
 

skrewler2

Senior member
Aug 28, 2005
279
0
76
In the past, you were right: version control systems held everything at a single site. But with modern distributed version control systems like Git, especially those that are open-source, the entire repository can go anywhere. So I'd say version control for commenting on versions is very much a good alternative these days.

Edit: P.S. If I ever do leave Git, I can dump the entire version history into a file or a set of comments first.

It is trivial to save history (inc commit messages) from SVN --> Git or Mercurial. I've also gone from Perforce to Git with no issues. I'm sure there are other scripts or utilities to do the same thing for whatever x SCM to y SCM.
 

Red Squirrel

No Lifer
May 24, 2003
67,907
12,375
126
www.anyf.ca
I do think code should be written so it is as self explanatory as possible. Then you only need small comment blocks to explain a class as a whole.

Something like:

Code:
/***********
Master class:  This class used to keep track of all run time information and memory management
***********/


Then in some cases maybe a comment to explain a block of code, or function.

Code:
//Now that we have the username and password, check to see if this user is allowed to access this part:

(several lines of code)


But commenting every single line, or adding HUGE blocks of comments is just insane. I knew someone who coded that way and it made it harder to follow the code. There was more comments than actual code.
 

LokutusofBorg

Golden Member
Mar 20, 2001
1,065
0
76
One of the biggest issues with comments is that you have to commit to maintaining them as source code. I can't count how times I've come across comments that Dev1 put on his code to be all nice to whoever came after him, and Dev2 made changes to the code, but didn't update the comment to reflect what he changed, so the comments don't apply anymore. When that happens, comments are *worse* than useless, they're a hindrance.
 

dwell

pics?
Oct 9, 1999
5,189
2
0
I agree about not using commits for revision history. Your SCM will keep track of changes complete with diffs, etc. If you're concerned about porting the rev history across version control systems, it's possible to import/export full repositories to and from any permutation of systems.
 

cKGunslinger

Lifer
Nov 29, 1999
16,408
57
91
One of the biggest issues with comments is that you have to commit to maintaining them as source code. I can't count how times I've come across comments that Dev1 put on his code to be all nice to whoever came after him, and Dev2 made changes to the code, but didn't update the comment to reflect what he changed, so the comments don't apply anymore. When that happens, comments are *worse* than useless, they're a hindrance.

I agree, but that's why I'm more in favor of smaller, localized comments. Comments such that when you change a (or few) lines of code, removing or changing the comments feels natural, and not a burden. Also, its easier for reviewers to catch these and make sure they stay aligned.

I can't stand huge block comments that describe - in detail - large sections of code. They are always out-of-date.

Ideally, you have a file-level comment, which should briefly describe what can be found in the file:
Code:
// FILE:        coordinate_conversions.c
// DESCRIPTION: Implements a variety of conversions between coordinate systems
A function-level comment that give a black-box explanation of the inputs and outputs, and any other considerations (blocking I/O, etc.)
Code:
// FUNCTION:    lla2ecef
// DESCRIPTION: Converts a geodetic coordinate triplet (lat, long, alt) into
//              a geocentric triplet (x, y, z).
// INPUTS:      WGS84 Coordinates (3x double-precision floats)
// OUTPUTS:     ECEF Coordinates (3x double-precision floats, meters)
// NOTES:       none

And the rest are small, but descriptive comments to explain reasoning, rationale, and intent about small blocks of code, or even mathematics formulas used:
Code:
// Compute X-coordinate:  X = [N + H] cos(lat) cos(lon)
<code here>

// Compute Y-coordinate:  Y = [N + H] cos(lat) sin(lon)
<code here>

// Compute X-coordinate:  Z = [(b 2 /a 2) N + alt] sin(lat)
<code here>
 

skrewler2

Senior member
Aug 28, 2005
279
0
76
One of the biggest issues with comments is that you have to commit to maintaining them as source code. I can't count how times I've come across comments that Dev1 put on his code to be all nice to whoever came after him, and Dev2 made changes to the code, but didn't update the comment to reflect what he changed, so the comments don't apply anymore. When that happens, comments are *worse* than useless, they're a hindrance.

I don't understand your point. You're basically saying that Jr Devs (or inept devs) do dumb things. This applies to adhering to coding standards, sensible commenting, following best practices, etc.
 

LokutusofBorg

Golden Member
Mar 20, 2001
1,065
0
76
I don't understand your point. You're basically saying that Jr Devs (or inept devs) do dumb things. This applies to adhering to coding standards, sensible commenting, following best practices, etc.

No, it's a lot easier to understand that the code has to be maintained as code, cause if you change some code or leave in unneeded code, then there's a higher chance you'll actually screw up the program logic.

Not so with comments, but the impact on maintainability is high enough that you *should* maintain comments with the same commitment level as real code.

I'll say it again, I've worked on lots of system where there were comments that weren't updated when the code was changed, and those comments being in there was worse than no comments at all.
 

KIAman

Diamond Member
Mar 7, 2001
3,342
23
81
Phew, I thought this was going to be a troll post but glad this turned into a serious discussion. As to commenting, do what is practical.

What I mean is that if you rely on automated documentation, then commenting is an absolute requirement. Other than that, you should always strive to write the most readable code within reason. Vertical space is cheap and you should make liberal use of it while horizontal space should be left within screen distance.

You should not go out of your way to do so if it reduces functionality in any way, but this should be rare as most modern languages reward readable code as far as functionality and performance. For example, enumeration, if vs case. The real focus of readable code should be a naming standard for your variables, method/function/class names and results/collections/arrays.

Now if you strive to make readable code, then at the minimum, you should always put a comment header on a method/function/class and a comment on your variable if the name isn't obvious for its intended purpose. Once again, do what's practical. You don't need to elaborate on a tiny little helper function, just a few words on what it does. As for huge functions or methods, you should provide a longer description, a list of inputs/outputs and an example of how to use it.
 

Evadman

Administrator Emeritus<br>Elite Member
Feb 18, 2001
30,990
5
81
There's a fine line. Tons of comments can make the code very hard to read. I don't need comments on each line. Can they be helpful and explanatory? Sure. But code needs to be readable and comprehensible, and if you need to comment every line in order to make what you're doing clear, something must be wrong. I typically write comments in the flowerbox before a method if the method does something unintuitive (but I try not to write unintuitive methods to begin with), and will occasionally write them in the body of a method if something really needs explaining, but those are rare. When I do have comments in the method body it's most often to mark something that is temporary, or a to-do, etc.


Comments are one way I judge my developers. People that comment every line are very inexperienced and unsure of their code. Thanks, I can see that line assigns a value to a variable. I didn't need a comment to tell me that

On the other hand, people that think their code is so magnificent that it doesn't need comments, and that anybody who can't figure it out without in seconds of viewing their digital gift to mankind is a boob who doesn't deserve to breathe the same air as them, is a disaster waiting to happen. Unless your software is developed from the ground up, never interacts with any other other systems, and never has to be maintained, you better have f'ing comments in your code or I'm going to fire your ass. All software eventually ends up with workarounds to deal with other parts of the code or other systems. Whether it's dealing with some quirk of whatever windowing environment you're using or telling a future programmer why some obscure table that appears to never be accessed has to be updated, there are a lot reasons to explain why a particular chunk of code needs to run.

There are lots of good comments in this thread, but I will just say; THIS. EVERYTHING THIS.
 

N4g4rok

Senior member
Sep 21, 2011
285
0
0
I do not know the industry view on it though.

It's a necessity for most projects. the reason being a lot of classes and libraries designed by a developer will be used by someone else who may not know and probably won't ever be able to speak to that developer. Documenting allows for something of a user's guide. And in larger scale applications, people are going to be working on smaller pieces. A few comments explaining the direction you were trying to go with a function/method/class is extremely helpful.

On that note, detailing return types, input specifications, and output formats are nice, but can get superfluous.
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,591
5
0
Comments are useful in conveying the thought process of the design.

Also commercial projects may not have the same comments requirements and projects for the government
 
sale-70-410-exam    | Exam-200-125-pdf    | we-sale-70-410-exam    | hot-sale-70-410-exam    | Latest-exam-700-603-Dumps    | Dumps-98-363-exams-date    | Certs-200-125-date    | Dumps-300-075-exams-date    | hot-sale-book-C8010-726-book    | Hot-Sale-200-310-Exam    | Exam-Description-200-310-dumps?    | hot-sale-book-200-125-book    | Latest-Updated-300-209-Exam    | Dumps-210-260-exams-date    | Download-200-125-Exam-PDF    | Exam-Description-300-101-dumps    | Certs-300-101-date    | Hot-Sale-300-075-Exam    | Latest-exam-200-125-Dumps    | Exam-Description-200-125-dumps    | Latest-Updated-300-075-Exam    | hot-sale-book-210-260-book    | Dumps-200-901-exams-date    | Certs-200-901-date    | Latest-exam-1Z0-062-Dumps    | Hot-Sale-1Z0-062-Exam    | Certs-CSSLP-date    | 100%-Pass-70-383-Exams    | Latest-JN0-360-real-exam-questions    | 100%-Pass-4A0-100-Real-Exam-Questions    | Dumps-300-135-exams-date    | Passed-200-105-Tech-Exams    | Latest-Updated-200-310-Exam    | Download-300-070-Exam-PDF    | Hot-Sale-JN0-360-Exam    | 100%-Pass-JN0-360-Exams    | 100%-Pass-JN0-360-Real-Exam-Questions    | Dumps-JN0-360-exams-date    | Exam-Description-1Z0-876-dumps    | Latest-exam-1Z0-876-Dumps    | Dumps-HPE0-Y53-exams-date    | 2017-Latest-HPE0-Y53-Exam    | 100%-Pass-HPE0-Y53-Real-Exam-Questions    | Pass-4A0-100-Exam    | Latest-4A0-100-Questions    | Dumps-98-365-exams-date    | 2017-Latest-98-365-Exam    | 100%-Pass-VCS-254-Exams    | 2017-Latest-VCS-273-Exam    | Dumps-200-355-exams-date    | 2017-Latest-300-320-Exam    | Pass-300-101-Exam    | 100%-Pass-300-115-Exams    |
http://www.portvapes.co.uk/    | http://www.portvapes.co.uk/    |