need help with comments, Im told to write more comments than code! so how do I articulate this?

can i get some tips from people who have had to read bad comments?

The Experts I have found to help me have extremely high standards and haven't really helped in anyway other than say; "comment everything, every line, more comments than code even!!"

I get the impression its a habit i will have to get in at uni, even though when i practice no one reads my code anyway and being inarticulate how would I comment on the code needed to write fiddley squidley maths? its self explanatory but it was still ignored by the family friends who i barely disturb for help (so i can use them later)
1
2
3
4
5
6
7
8
9
10
11
12

        int a=1,b,c=1;
        //some integers for maths
        while (a<1000)
        {
        cout<<a<<endl;
        b= a+c;
        //b is now last number plus present number
        c=a;
        //a is c
        a=b;
        }

my problem with above (i know its not right its just an example) is that theres no explantaion for whats happening other than numbers doing stuff to get Fibonaci sequence.
Good comments in your code are for you as much as for others reading it. Have you ever gone back to code you wrote a year ago and had to spend time figuring out what you were doing? Commenting every line is overkill and can make the code just as hard to read as if it was uncommented. Comment anything that isn't immediately obvious what you are doing, and have a comment block for functions and class methods describing what they do.
I'm not very good at commenting code myself to be honest. I think the reason why they tell you to comment everything is because most people learn by doing and while learning it's better to do too much than too little. Most people get lazy and will do too little eventually anyway so then it's better to have more experience.

The comments in your code are not helpful at all. They doesn't give any more information than the code is already doing so better read the code. What probably should have a comment saying is that you are generating the Fibonaci sequence up to 1000. To me that would be enough. If you used a specific algorithm you could mentioned that too.
Last edited on
One obvious thing is to put comments on the same line or before the statement. Putting them after-ward is a little crazy IMO.

The comments you have in the code above aren't very helpful at all - //a is c is just a waste of time.

You don't have to comment everything, comments are worthwhile if they are helpful. Having meaningful names for variables is a really good idea - try to make the code self documenting in this respect. Then use comments to put helpful info like max & min ranges, but even that might become obvious with the input validation code.

Edit: I like to declare variables 1 per line so you have the opportunity to comment them if required.

Functions should have several lines explaining what the function does.

Also remember that people aren't mind readers, the clearer and simpler things are the better (not to take away from elegance). Other people might have to read your code, and you might have to read your own code in 1 or 2 years time - it's good not to be embarrassed by not understanding your own code!

Don't be afraid to put a URL for the original problem into a comment. Use comments to explain the variable naming strategy used. This is handy when things get complicated.

For example one of the things I am doing at the moment is writing code to implement all the stuff in this document:

http://www.icsm.gov.au/gda/gdatm/gdav2.3.pdf


So I wrote comments to explain how I arrived at my variable names:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/////////////////////////////////////////////////////////////////////
//
// http://www.icsm.gov.au/gda/gdatm/gdav2.3.pdf
// Vicenty's Inverse Formulae
// Chapter 4, page 15 - page 20 in pdf
//   glossary on page 55 of pdf
//
// Variable naming:
//  prepend m_ for member variables
//  variables named as per documentation above
//  Greek letters are lower case words for lc Greek
//    but CamelCase when combined with a trig function
//  Numerical subscripts are literal numbers
//  ^ (exponent) & * (multiply) have been added to pasted Formulae
//  to make meaning more clear 


I copied & pasted the formulae into comments as well :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
double CGDA94::IterateSigma() {

/////////////////////////
// There is no error checking in this code at all
/////////////////////////

   //TanU1 = (1-f) Tanφ1
   m_TanU1 = m_1minusf * tan(m_phi1) ;
   //TanU2 = (1-f) Tanφ2
   m_TanU2 = m_1minusf * tan(m_phi2) ;

   m_U1 = atan(m_TanU1);
   m_U2 = atan(m_TanU2);

   // Starting with the approximation,
   // λ = ω = λ2 - λ1
   m_omega  = m_lambda2 - m_lambda1;
   m_lambda = m_omega;

   //Iterate the following equations, until there is no significant change in σ:
   //no significant change in sigma
   //Functions named EquationA1 to EquationA7 to match the 7 in document

   m_sigma = 0.0;
   for (int count = 0 ; count < MAXSIGMAITER ; ++count) {
      m_SinSqSigma = EquationA1();
      m_SinSigma  = sqrt(m_SinSqSigma);

      m_NewSigma = asin(m_SinSigma) ;

      if(std::abs(m_NewSigma - m_sigma ) < SIGMAPREC) {
         return m_NewSigma;
      }

      m_sigma = m_NewSigma;

      m_CosSigma   = EquationA2();
      m_TanSigma   = EquationA3();
      m_SinAlpha   = EquationA4();
      m_alpha      = asin(m_SinAlpha);
      m_CosAlpha   = cos(m_alpha);
      m_CosSqAlpha = m_CosAlpha * m_CosAlpha;
      m_Cos2SigmaM = EquationA5();
      m_CosSq2SigmaM = m_Cos2SigmaM * m_Cos2SigmaM;
      m_C          = EquationA6();
      m_lambda     = EquationA7();
   }
return m_NewSigma;
}


1
2
3
4
5
double CGDA94::EquationA4() {
   //Sinα = CosU1 CosU2 Sinλ / Sinσ

   return ( cos(m_U1)*cos(m_U2)*sin(m_lambda) )/ m_SinSigma;
}


This might seem overkill to some, but I found it easy to copy & paste all the formulae first, then write the code after, to help avoid any screw ups.

Just to reiterate - this is not the final version of the code.

HTH

Last edited on
EDIT: Got interrupted while writing this, and got ninja'd. Hope some of this is useful anyway.

Imagine that, in 5 years time, you're going to have to look again at your code, and understand what it does, and why. What could you write in comments now, that would help the future you make sense of it?

Stuff like explaining algorithms, explaining what the variables are used for, etc, are all useful. Also, any oddities or "clever tricks" in your code that wouldn't be immediately obvious to someone are worth explaining.

Stuff that's really obvious - or just rewriting the line of code in English - is not useful, and is just clutter. For example:
 
i++; // Increment i 

is stupid. And yes, I have seen comments like that - buried in the middle of hundreds of lines of otherwise uncommented mathematical algorithms!

So, something like "some integers for maths" really isn't helpful to anyone. But explaining what a, b, and c represent would be. Explaining why a and c are initialised to 1 would be helpful - why 1? And why is b not initialised? Why 1000 in your loop, rather than any other?

It doesn't even state anywhere that your code is supposed to generaste a Fibonnaci sequence. That would be a good start!

Yes, this particular example has maths so simple that most people could understand it anyway. But this is a learning exercise, and learning how to write code that is easy to understand and maintain is important to being a good developer, as well as just writing code that implements the functionality. You're not adding comments because this bit of code desperately needs them; you're adding comments because you're learning the art of commenting your code.

I'll also add that the idea of writing "more comments than code" is somewhat old-fashioned. These days, developers tend to favour making their code easier to understand by making it "self-commenting" - in other words, by using names for variables that make it obvious what they're for; ditto for functions, methods and classes. Also, structuring your code into easily-understood components helps.

Be that as it may, I'd still prefer to look at code where the original developer has erred on the side of putting in too many comments, rather than one with too few.
Last edited on
If you write good code (sensible names for everything) you shouldn't have to comment much. Just describe the functionality of a class as a whole, how it interacts with other classes, and you should be good. If you have overly complex functions then you can write a brief comment explaining how they work as well.
> The Experts I have found to help me ... say;
> "comment everything, every line, more comments than code even!!"

Here's what one expert has to say:
Comments

A delicate matter, requiring taste and judgement. I tend to err on the side of eliminating comments, for several reasons. First, if the code is clear, and uses good type names and variable names, it should explain itself. Second, comments aren't checked by the compiler, so there is no guarantee they're right, especially after the code is modified. A misleading comment can be very confusing. Third, the issue of typography: comments clutter code.

But I do comment sometimes. Almost exclusively, I use them as an introduction to what follows. Examples: explaining the use of global variables and types (the one thing I always comment in large programs); as an introduction to an unusual or critical procedure; or to mark off sections of a large computation.

There is a famously bad comment style:

i=i+1; /* Add one to i */

and there are worse ways to do it:

1
2
3
4
5
6
7
        /**********************************
         *                                *
         *          Add one to i          *
         *                                *
         **********************************/

                       i=i+1;

Don't laugh now, wait until you see it in real life.

Avoid cute typography in comments, avoid big blocks of comments except perhaps before vital sections like the declaration of the central data structure (comments on data are usually much more helpful than on algorithms); basically, avoid comments. If your code needs a comment to be understood, it would be better to rewrite it so it's easier to understand.
- Rob Pike in 'Notes on Programming in C' February 21, 1989 http://www.lysator.liu.se/c/pikestyle.html


So avoid this a,b,c,d,e,f... kind of stuff int a=1,b,c=1;

As far as possible, let your code speak for itself. In most cases, well-written code is far more eloquent than anything one could append as comments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int main() // print the fibonacci sequence starting with 1 upto an upper bound
{
    constexpr int UPPER_BOUND = 1000 ;

    int prev_to_last_term = 0 ;
    int last_term = 1 ;
    int current_term = 1 ;

    while( current_term  < UPPER_BOUND )
    {
        std::cout << current_term << '\n' ;

        current_term = last_term + prev_to_last_term ;

        // move sliding window forward by one term
        // (comment aimed at newbies who have just started learning to program)
        prev_to_last_term = last_term ;
        last_term = current_term ;
    }
}




I like explaining how you got to variable names, in my little projects i use things like "thing", "temp2" and "whatever" i think its time i started being more professional and collaborating,

this is really good, actually theres the best arguments and explanations on the subject, I bet this will help in uni at some point.
cheers guys, im beggining to think i could even post problems on stack overflow now
Last edited on
@mikeyboy, thats a good argument for commenting your own code, it never occured to me i will be coming back and thinking "the hell is this"
Topic archived. No new replies allowed.