Development How do you comment code?

Discussion in 'Software' started by GuardianStorm, 9 Jul 2006.

  1. GuardianStorm

    GuardianStorm Minimodder

    Joined:
    26 Apr 2005
    Posts:
    1,475
    Likes Received:
    1
    this isnt a topic about me not knowing how to comment code :worried:

    my question is, how do you lot comment your code?

    i put the standart xml comments for function & sub descriptions (for thos who dont know, put a a blank line above the function/sub and press: ''' for vb and /// for c#)

    but what about inside functions?

    i tend to comment after the line of code, and keep all comments in line:
    Code:
    code				'comment
    longer code			'comment
    yet more code			'comment
    some stuff			'comment
    a really long line of code that goes past my comment line	'comment
    
    but now that i have a summer placement programming, im starting to comment above the line of code:
    Code:
    'draws a box stuff
    code
    'draws a circle
    code
    
    but my problem with that is the code dosent look as clean imo, as all your code blocks get broken up by the comments :(

    any thoughts? how do you comment your code?

    ...

    or are you evil and not comment your code :eeek:
     
  2. Nath

    Nath Your appeal has already been filed.

    Joined:
    28 Dec 2003
    Posts:
    2,409
    Likes Received:
    1
    If I need to write quite a long comment I tend to do this:

    PHP:
    <?php
    function setParam($paramName,$paramValue) {

        
    /*
        Just a function for setting article params cause I'm far
        too lazy to have individual getters/setters. No error
        checking cause tbh it's my code and I know how it works.
        */

        
    $this->{$paramName} = $paramValue;
    }
    ?>
    Looks quite neat imho and doesn't particularly break up the code to a level where it's unreadable.
     
  3. Rich_13

    Rich_13 What's a Dremel?

    Joined:
    12 Feb 2003
    Posts:
    730
    Likes Received:
    0
    This is prob a bit weird but i'll use descriptive words as end of line for comments and then if i need to explain more fully i'll do so at the end of that block of code...
     
  4. Firehed

    Firehed Why not? I own a domain to match.

    Joined:
    15 Feb 2004
    Posts:
    12,574
    Likes Received:
    16
    Usually I'll explainfull/large functions at the beginning as per the second block, but TBH I tend to switch between the end-of-line and before-the-line for smaller bits. Usually any of the more obscure or complex functions that still fit on one line get commented at the end of the line, where any multi-line code OR comments go beforehand (like a block $_GET[];s tend to get an explanation of each var all at once, not per-line).

    I'm quite inconsistant about it, but then again I'm the only one looking at my code so it neither gets as many comments as it should nor really matters as long as I can figure out what I meant later on.
     
  5. RTT

    RTT #parp

    Joined:
    12 Mar 2001
    Posts:
    14,120
    Likes Received:
    74
    Sparingly :)

    Seriously though...

    Code:
    /**
      * This is a 
      * multi line
      * comment
      */
    
    // and this is a single line comment
    
    I don't really have any set pattern for how i use them, but if i'm commenting a lot of code to make what i'm doing ultra clear, i block the comments to the right after the code, like...

    Code:
    lots and lots;				// this                       
    of code doing lots;			// comment block
    and lots of stuff;			// comments the code
    that isnt so easy to follow;		// to the left
    yada yada;				// quite
    yada;					// nicely
    
     
  6. DougEdey

    DougEdey I pwn all your storage

    Joined:
    5 Jul 2005
    Posts:
    13,933
    Likes Received:
    33
    i agree with RTT. I normally have a multi line comment "box" before ech function, inputs, outputs, etc...

    And then comment if the code is not obvious
     
  7. Xiachunyi

    Xiachunyi What's a Dremel?

    Joined:
    3 Nov 2003
    Posts:
    1,404
    Likes Received:
    0
    I am one of those people that comment above as well as to the side of the code depending on how lazy I am. (Where my cursor is at the moment I think to comment)

    Example:
    Code:
    //~~~~~Query Dialog Box
    BOOL CALLBACK Query_Dialog(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
    {
        static HBITMAP hBitmap;
        static HDC hDc;
        static HDC hImageDc;
        static HBITMAP hOldBitmap;
    
        switch(message)
        {
            static HBRUSH hbBackground;
    
            case WM_INITDIALOG:
            {
            //Setup Bitmap
                hBitmap = (HBITMAP)LoadImage(hInstance, "Data\\Graphics\\Splash.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
                hDc = GetDC(hwnd);
                hImageDc = CreateCompatibleDC(hDc);
                hOldBitmap = (HBITMAP)SelectObject(hImageDc,hBitmap);
                BitBlt(hDc, 0, 0, 350, 263, hImageDc, 0, 0, SRCCOPY);
    
            //Send local dialog box handle to global
                hQuery = hwnd;
    
            //Fill Combo Box
                DEVMODE dms;
                char buffer[256]  = {0};
                int iCount = 0, iKeep = 0, iIndex = -1, iSafety = -1;
    
                while(EnumDisplaySettings(NULL, iCount++, &dms))
                {
                    if(dms.dmBitsPerPel < 16) //Bit Depth Less than 16 will not display
                    {
                        continue;
                    }
    
                    if(Option.iXres == 0 || Option.iYres == 0 || Option.iBitRes == 0) //If User Stipulated Defaults do not Exist
                    {
                        if((GetDeviceCaps(hDc, HORZRES) == dms.dmPelsWidth) && (GetDeviceCaps(hDc, VERTRES) == dms.dmPelsHeight) &&
                                (GetDeviceCaps(hDc, BITSPIXEL) == dms.dmBitsPerPel) && (GetDeviceCaps(hDc, VREFRESH) == dms.dmDisplayFrequency)) //Reserve Default
                        {
                            iIndex = iKeep;
                        }
                    }
                    else
                    {
                        //Retrieve User Stipulated Defaults and Compare to Supported Modes
                        if((dms.dmPelsWidth == Option.iXres) && (dms.dmPelsHeight == Option.iYres) &&
                                (dms.dmBitsPerPel == Option.iBitRes) && (dms.dmDisplayFrequency == Option.iFrequency)) //Set to Default
                        {
                            iIndex = iKeep;
                        }
                    }
    
                //Fill in choices
                    sprintf(buffer, "%dx%d, %d bit @ %dHz ", dms.dmPelsWidth, dms.dmPelsHeight, dms.dmBitsPerPel, dms.dmDisplayFrequency);
                    SendMessage(GetDlgItem(hwnd, IDC_QUERY_DISP), CB_ADDSTRING, 0, (long)buffer);
    
                    iKeep++;
                }
                if(iIndex == -1) //If Stipulated Defaults are Invalid, Retrieve Current ScreenMode
                {
                    iCount = 0;
                    iKeep = 0;
    
                    while(EnumDisplaySettings(NULL, iCount++, &dms))
                    {
                        if(dms.dmBitsPerPel < 16) //Bit Depth Less than 16 will not display
                        {
                            continue;
                        }
                        if((GetDeviceCaps(hDc, HORZRES) == dms.dmPelsWidth) && (GetDeviceCaps(hDc, VERTRES) == dms.dmPelsHeight) &&
                                (GetDeviceCaps(hDc, BITSPIXEL) == dms.dmBitsPerPel) && (GetDeviceCaps(hDc, VREFRESH) == dms.dmDisplayFrequency)) //Reserve Default
                        {
                            iSafety = iKeep;
                        }
                        iKeep++;
                    }
                    //Since Defaults obtained from the XML Options file are invalid, replace them with current display settings
                    /*
                    WritePrivateProfileString("ScreenMode", "Width", "0", Option.cIniPath);
                    WritePrivateProfileString("ScreenMode", "Height", "0", Option.cIniPath);
                    WritePrivateProfileString("ScreenMode", "BitRes", "0", Option.cIniPath);
                    WritePrivateProfileString("ScreenMode", "Frequency", "0", Option.cIniPath);
                    WritePrivateProfileString("ScreenMode", "FullScreen", "0", Option.cIniPath);
                    WritePrivateProfileString("ScreenMode", "Maximize", "0", Option.cIniPath);
                    */
                }
    
            //Setup Defaults if exists
                if(iSafety == -1)
                {
                    SendMessage(GetDlgItem(hwnd, IDC_QUERY_DISP), CB_SETCURSEL, iIndex, 0);
                }
                else
                {
                    SendMessage(GetDlgItem(hwnd, IDC_QUERY_DISP), CB_SETCURSEL, iSafety, 0);
                }
                if(Option.bFullScreen)
                {
                    CheckDlgButton(hwnd, IDC_QUERY_FS, BST_CHECKED);
                }
                if(Option.bMaximize)
                {
                    CheckDlgButton(hwnd, IDC_QUERY_MAX, BST_CHECKED);
                }
    
            //Create Brush Color
                hbBackground = CreateSolidBrush(RGB(0, 0, 0));
            }
            break;
    
            case WM_CTLCOLORDLG:
            case WM_CTLCOLORSTATIC:
            case WM_CTLCOLOREDIT:
            {
                SetTextColor((HDC)wparam, RGB(80, 80, 255));
                SetBkMode((HDC)wparam, OPAQUE);
                SetBkColor((HDC)wparam, RGB(0, 0, 0));
                return (INT_PTR)hbBackground;
            }
            break;
    
            case WM_PAINT:
            {
                BitBlt(hDc, 0, 0, 450, 263, hImageDc, 0, 0, SRCCOPY);
            }
            break;
    
            case WM_COMMAND:
            {
                switch(LOWORD(wparam))
                {
                    case IDC_QUERY_PLAY:
                    {
                        DEVMODE dms;
                        int iIndex = 0;
    
                    //Check and Declare Screen Mode
                        iIndex = SendMessage(GetDlgItem(hwnd, IDC_QUERY_DISP), CB_GETCURSEL, 0, 0);
    
                        if(iIndex == CB_ERR)
                        {
                            MessageBox(hwnd, "Invalid Screen Mode Selection", "Error", MB_OK | MB_ICONERROR);
                            break;
                        }
    
                    //Check for fullscreen flag
                        if(IsDlgButtonChecked(hwnd, IDC_QUERY_FS) == BST_CHECKED)
                        {
                            Option.bFullScreen = TRUE;
                        }
                        else
                        {
                            Option.bFullScreen = FALSE;
                        }
    
                    //Check for Maximize flag
                        if(IsDlgButtonChecked(hwnd, IDC_QUERY_MAX) == BST_CHECKED)
                        {
                            Option.bMaximize = TRUE;
                        }
                        else
                        {
                            Option.bMaximize = FALSE;
                        }
    
                        int iCount=0, iKeep=0;
    
                        while(EnumDisplaySettings(NULL, iCount++, &dms)) //Match index with DisplaySettings Index
                        {
                            if(dms.dmBitsPerPel < 16) //Bit Depth Less than 16 will not display
                            {
                                continue;
                            }
                            iKeep++;
                            if(iKeep > iIndex)
                            {
                                Option.iXres = dms.dmPelsWidth;
                                Option.iYres = dms.dmPelsHeight;
                                Option.iBitRes = dms.dmBitsPerPel;
                                Option.iFrequency = dms.dmDisplayFrequency;
    
                                break;
                            }
                        }
    
                    //Write given options to the XML Options file
                        if(IsDlgButtonChecked(hwnd, IDC_QUERY_DEFAULT) == BST_CHECKED)
                        {
                            WriteOptionXml(XML_WRITE_SCREENMODE);
                        }
    
                        EndDialog(hwnd,0);
                    }
                    break;
    
                    case IDC_QUERY_UPDATE:
                    {
                    }
                    break;
    
                    case IDC_QUERY_EXIT:
                    {
                        Control.bDone = TRUE;
                        EndDialog(hwnd, 0);
                    }
                    break;
                }
            }
            break;
    
            case WM_CLOSE:
            case WM_DESTROY:
            {
                DeleteObject(hbBackground);
                SelectObject(hImageDc, hOldBitmap);
                DeleteObject(hBitmap);
                ReleaseDC(hwnd, hDc);
                DeleteDC(hImageDc);
                return TRUE;
            }
        }
        return FALSE;
    }
    
     
  8. RTT

    RTT #parp

    Joined:
    12 Mar 2001
    Posts:
    14,120
    Likes Received:
    74
    I also do this which I guess is a form of commenting in any language that isn't strongly typed...

    Code:
        function foo(/* string */ $bar, /* array */ $yada)
        {
         ......
        }
    
     
  9. eek

    eek CAMRA ***.

    Joined:
    23 Jan 2002
    Posts:
    1,600
    Likes Received:
    14
    For methods and classes I tend to follow JavaDoc (no matter what the language)

    Once inside methods I don't really do much commenting as more often than not it is fairly self explanetory and as I make such heavy use of classes and methods blocks of code tend to be quite small. If I do make comments though I do it as follows (all my lines are = to or < 80 chars long):

    if room for code and comment <= 80 chars then all on one line:
    Code:
    code here // comment here
    more code here // another comment here
    final bit of code // comment
    if adding comment will take it over 80chars then:
    Code:
        code here
            // align comment with code and place it after
     
  10. steveo_mcg

    steveo_mcg What's a Dremel?

    Joined:
    26 May 2005
    Posts:
    5,841
    Likes Received:
    80
    I prefer to coment in a block before a group of commands. But since most of the programming i do is vba in work its not entirely neccessary since even a newb can decode vba pretty quickly. I know thats the wrong attitude but i'm getting laid off soon so i don't give a monkeys!
     
  11. JuMpErFLY

    JuMpErFLY Minimodder

    Joined:
    13 Mar 2003
    Posts:
    882
    Likes Received:
    1
    Above the code, it may break it up - but that's useful, makes it easier to find things. Above makes sense, I want to read what a piece of code does before reading the code itself.
     
  12. dfhaii

    dfhaii internets

    Joined:
    24 Mar 2002
    Posts:
    520
    Likes Received:
    0
    I'm bad and don't comment much tbh, but when i do it's generally

    lineOfCode //do this and that

    or
    /* describe what's happening */
    function beans (String LOLOL, int K){

    etc.

    I tend to put them in where they may be useful rather than the

    $beans = 1; //LOLOL MAKE $beans contain the integer 1

    i see plastered all over the interwebs.
     
  13. MiT

    MiT Don't feed me after midnight!! nom

    Joined:
    18 May 2005
    Posts:
    736
    Likes Received:
    12
    I am the same as Xiachunyi. I put comments above and on the side, and also on top. It all depends on how complicanted the code is. If it gets too scary, then i place a big block comment on the top of the page, explaining what the whole code does. Then a comment above each function, then if it need too, i comment individual lines. Only the ones, that are hard to follow.
     
  14. Hwulex

    Hwulex What's a Dremel?

    Joined:
    1 Feb 2002
    Posts:
    4,007
    Likes Received:
    1
    That's one of the evilest things I've ever seen! :eeek:

    Just get yourself a JavaDoc (phpDoc) enabled IDE, like Zend, and use that. Hoorah!


    So yeah, I use phpDoc (JavaDoc) syntax for commenting classes, functions, etc.

    For large comments I use blocks in /* comment */ syntax. Single lines are commented by doube-slash //.

    For large numbers of nested loops and conditions, I will comment the closing brace with a # hash comment (in PHP).

    I don't put comments to the side. They'd too easily go all fubar when editing stuff.

    PHP:
    /**
     * Function that does some stuff, woo.
     * @param int item I want to do stuff with
     * @return array
     */
    function doStuff$idItem ) {
      
    // Initialise variable
      
    $arrStuff = array();

      
    // Loop for loopy loop's sake
      
    foreach ( get_stuff$idItem ) as $intStuff ) {
        
    $arrStuff[$intStuff] = $arrStuff[$intStuff] += $intStuff ;
      } 
    # end foreach

      
    return $arrStuff;
    }
    That sort of thing.
     
    Last edited: 12 Jul 2006
  15. OneSeventeen

    OneSeventeen Oooh Shiny!

    Joined:
    3 Apr 2002
    Posts:
    3,454
    Likes Received:
    2
    I'm with Hwulex, phpDoc, with extra one-liners inside the functions...
    here's my example from a horrible file upload class I wrote a while back.
    PHP:
        /**
         * Check for errors in the upload
         * 
         * @param string $fieldName Name of the HTML File Field to check, 
         * which will be urlencoded for added safety.
         * @return true|false
         */
        
    public function checkFile($fieldName)
        {
            
    //clear out the old file details:
            
    $this->fileDetails = array();
            
            
    //check that the allowable file suffixes are set first
            
    if(!is_array($this->allowedFileTypes) || count($this->allowedFileTypes)<=0) {
                
    $this->error "The Allowed File Types was not set, please call 
                    setFileSuffix() first to establish allowable file types."
    ;
                return 
    false;
            }
            
    //check that the field name was set and is not blank
            
    if(strlen(trim($fieldName))<=0){
                
    $this->error "The Field Name was not received or was invalid.";
                return 
    false;
            } else {
                
    $fieldName urlencode($fieldName);
            }
            ...
    snip...
            return 
    true;
        }
     
  16. simon w

    simon w What's a Dremel?

    Joined:
    3 Nov 2003
    Posts:
    1,302
    Likes Received:
    0
    Same as Hwulex, except the opening { should be on a new line.
     
  17. Draxin

    Draxin Seeker of Photons

    Joined:
    29 Nov 2001
    Posts:
    965
    Likes Received:
    5
    i tend to coment just about everything
     
  18. Lazlow

    Lazlow I have a dremel.

    Joined:
    8 Aug 2003
    Posts:
    1,464
    Likes Received:
    0
    I'm the same, as I was pretty much taught to code and comment like this. I find that putting comments before a line of code (as above) makes it clearer and easier to edit the actual line of code. A block quote before major things is useful for introducing them too.
     
  19. will.

    will. A motorbike of jealousy!

    Joined:
    2 Mar 2005
    Posts:
    4,461
    Likes Received:
    20
    With css, my comments are like this:

    Main sections:

    Code:
    /*== DEFAULT PAGE STYLES
    --------------------------------------------*/
    Secondary Sections:

    Code:
    /*== Page header ==*/
    Quick notes

    Code:
    /*Shifts text 1px left*/
    At the top i have a whole host of different things like base color references and page widths padding etc just so that i don't have to keep measuring stuff in photoshop.

    I like to think my code is easy to read. Although i wish dreamweaver would bring in some kind of indexing feature so that you can quickly click down to whichever section you want. Ctrl+F is tedious and brings up that crap panel that makes even the hugest of screens look weeney.
     
  20. Hwulex

    Hwulex What's a Dremel?

    Joined:
    1 Feb 2002
    Posts:
    4,007
    Likes Received:
    1
    Depends which standards you're working to. At my office, it's my standard, so they go on the same line. :p :D :naughty:

    It does have a real name and history, besides "mine", but it's on the wiki at work and I can't be arsed to VPN and find out.
     

Share This Page