Jump to content

What's your Comment Policy?

- - - - -

  • Please log in to reply
5 replies to this topic

#1
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Anyone who's maintained software long enough knows the value of well-placed, explanatory comments. Good comment work can make the difference between a 10 minute tweak and a 6 hour code revision, so we all (or at least most of us), but a few comments in here and there to, at the very least, remind ourselves what exactly we were thinking when we wrote the code. Well, this post is for you to talk about how you go about commenting. Explain, if you will, what you do when faced with the need to explain yourself?

If anyone's seen my recent code, they'd know I'm very liberal with my spacing and I comment like a freak. This is because I actually write my comments before my code, and I use those comments as the basis for how I write the code. I essentially write what I want to do, and an explanation of how I intend on doing it, and then write the code that does it. If there's problems, I rewrite my comment and change the code. This has given me a significant advantage when I go back and start looking at this code again, since if nothing else it allows me to know what I was thinking, which is important as it gets me back into the mindset.

My comments have a sort of "flow of consciousness" feel to them, which does present what many people would say is a problem, IE I have too many superfluous comments. However, I've made it a point to work on hedging my comments when I'm done and all-in-all I'd say it looks pretty good.

What do you do? I'm on my lunch break right now or I'd provide examples... I'll post some when I get back from work. Until then... I'd like to see yours!
Wow I changed my sig!

#2
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
In my stuff, before any code is seen, I try to provide a description of how I decided to implement things. It gives the reader the big picture. The big picture will give an idea of the program's control flow, like where it starts and where it dives into certain functions. Throughout my code, I usually have descriptions of the specifics. I write what each function/code block/variable does and why. While I'm coding, I kind of do the same thing you do, Zeke. I tend to write comments before I program the code. I also write the program with functions that I haven't implemented yet.

I'll use THRASH as an example. It's something that (sadly) never took off, due partially to the fact that my old code sucked and I reprogrammed it from scratch. I won't post the README, makefile or header files, but I'll attach a zip file for anyone interested in those.

main.c:
/* As of now, thrash is a pretty simple program. The main()
   function includes two subfunctions, getinput() and
   execute(). They are pretty self-explanitory.

   getinput() displays the prompt and gets input from the
   command line. Underneath, getinput() can use GNU readline
   or any other method of getting input from the user. Input
   is stored into the char double pointer, input.

   execute() takes the input, parses it, then executes either the
   internal command or system command. */


#include <stdio.h>
#include <stdlib.h>
/* declares the execute() function */
#include "execute.h"
/* declares the getinput() function */
#include "input.h"


int main(int argc, char **argv) {
    /* This double pointer is intentional! */
    char **input=malloc(sizeof(char*));
    /* retval gets the return value of each function,
       so they can be tested for errors/stop points */
    int retval;
    while (1) {
        /* getinput dynamically allocates memory
           The input pointer is free()'d after it's used
           by execute(). */
        retval=getinput(input);
        if (retval==0) {
            free(input);
            return 0;
        }
        retval=execute(*input);
        if (retval==0) {
            return 1;
        }
        free(*input);
    }
    return 0;
}
input.c:
/* This defines the getinput() function.
   Right now, it simply uses GNU readline, but
   an alternate standard c way of getting input is
   commented out in case readline is undesirable. */

#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>

int getinput(char **str) {
    /* printf("-]");
    fflush(stdout);
    *str=malloc(sizeof(char)*1024);
    if (*str==NULL) {
        return 0;
    }
    if (fgets(*str, 1024, stdin)==NULL) {
        printf("\n");
        return 0;
    }
    return 1; */
    *str=readline("-]");
    return 1;
}
execute.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* These headers are needed for the awesome
   POSIX way of executing binaries :) */
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int execute(char *str) {
    /* Here we split the command line
    input into tokens. Example:
    "ls -l" will now be "ls" and "-l"
    The tokens are stored into char** token; */

    char **token=malloc(sizeof(char*));
    /* temporary pointer */
    char **temp;
    int i=0;
    token[i]=strtok(str, " \n");
    while (token[i]!=NULL) {
        i++;
        temp=realloc(token, sizeof(char*)*(i+1));
        /* Check that the memory was allocated properly */
        if (temp==NULL) {
            free(token);
            perror("realloc");
            return 0;
        }
        token=temp;
        token[i]=strtok(NULL, " \n");
    }
    /* Read list of internal commands (not implemented yet)
       I'll probably have an internal.c file or similiar for
       these functions:
        
       if (checkinternal(token[0])==1) {
           executeinternal(inargc, token);
       } */
    
    /* Execute external binary
       Here, we fork() a sub-process. (the child)
       The sub-process is replaced with the program
       that is to be executed using execvp() */
    pid_t pid;
    pid=fork();
    if (pid<0) {
        /* Standard error checking, in case fork() fails */
        perror("fork");
        return 0;
    }
    if (pid==0) {
        /* We pass the tokenized input to execvp for execution.
           The binary will be called, and the arguments will be
           passed to it. */
        if (execvp(token[0], token)==-1) {
            perror("execvp");
            return 0;
        }
    }
    /* wait for child to end, then return success */
    int status;
    waitpid(pid, &status, 0);
    return 1;
}

Attached Files


Edited by Guest, 02 February 2011 - 12:55 PM.
syntax highlighting :)

Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#3
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
Well looking through one of my old programs I have less than 10 comments for 1500 line's of code. :c-thumbdown:

Recently though I started using comments alot more, since its about impossible to re-write code without good comments.
I also like to figure out how I want to the code to work in comments, and then proceed to code it. But I mostly just try to comment out anything that would be confusing to me if I hadn't coded in a while.
Example of something that could be confusing.
string[] workerData = new string[4] { textBox1.Text, numericUpDown1.Value.ToString(), numericUpDown2.Value.ToString(), numericUpDown3.Value.ToString()};[COLOR=green]//Add Control values to array.[/COLOR]
ListViewItem newItem = new ListViewItem(workerData); [COLOR=green]//Create New listView Item, with the value's of the array.
//Note: the first value of the array will fall under the first column of the listView and the second value into the second column ect...[/COLOR]
listView1.Items.Add(newItem);
I also like to keep a, "todo" & "done", list in my code. :)
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
My code tends to be pretty low on comments, but i also have to produce functional and technical specs when I'm at work. It helps a lot when there is separate documentation about what should be happening, and bug/feature tracking tied to each code change.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
Depending on what is to be written, if it is for a closed project and there are many files of which I am writing, some hinting comments can be useful here. Take for example this ancient implementation of strtok.

What people often ask for are not for comments about how they work, rather what they exactly are. I could rewrite that using a Javadoc style syntax using Doxygen, which then makes the client happy!
/**
  * @file strtok.c
  * Parse S into tokens delimited by DELIM. If S were to be NULL,
  * the last string passed to strtok() will be called.
  * @example examples/strtok.html
 */
#include <string.h>

/**
 * Holds last token if str is null.
 */    
static char *olds;

#undef strtok

/**
 * @param[in] s The string to tokenize
 * @param[in] delim The delimiter of s
 * @return A pointer to the last token in s
 * @retval NULL A null pointer if no tokens are left to retrieve
 */
char *strtok( char *s, const char *delim ) {

   /**
    * Holds the current token.
    */    
  char *token;

  if (s == NULL)
    s = old;

  s += strspn (s, delim);
  if (*s == '\0')
    {
      oldstr = s;
      return NULL;
    }

  token = s;
  s = strpbrk (token, delim);
  if (s == NULL)
    olds = __rawmemchr (token, '\0');
  else
    {
      *s = '\0';
      olds = s + 1;
    }
  return token;
}
I much prefer the gains from writing commenting like that, so if I am writing something that will go somewhere I will do it like that.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#6
cdg10620

cdg10620

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 389 posts
Most of my programming is shared between me and one other developer. I typically tend to comment a function or line of code only if I feel that it needs explanation of what it's true purpose is or what the function was intended for. Most of my comments look like this:

This example is from a javascript file that was used in an asp.net MVC / ExtJs project that I wrote:


addDetail: function(btn, ev) {

        var id = 0;

        if( this.getStore().data.items.length > 0 )

            id = this.getStore().data.items[0].data["VoucherId"];

             

        var VoucherDetail = this.createRecord();

        var vd = new VoucherDetail({

            // Doing this adds it to the grouping so that the total is

            // added with the rest of the detail items.

            VoucherId: id,

            CompanyCode: '0000',

            GlCode: '',

            ProjectCode: '',

            ProjectPhase: '',

            ProjectTask: '',

            AllocationCode: '',

            Description: 'PED',

            Amount: 0,

            active: true

        });

        this.editor.stopEditing();

        this.getStore().insert(0, vd );

        this.getSelectionModel().selectRow(0);

        this.editor.startEditing(0);

    },


The only reason that I added those lines of comments is because I felt like I needed to explain why I was setting the voucherId = id in the object definition. This helped me later after I forgot why I had done that.

I should probably be better at commenting my code, but most of the time I'm worried more about what it does for me since most of the time i'm the only person who looks at it.
-CDG10620
Software Developer




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users