Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Commenting your code: RIGHT or WRONG way?

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    22
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Commenting your code: RIGHT or WRONG way?

    From an experienced Programmers point of view, or any level of Programers point of view. What would be a right way of commenting your code. What should I note and what should I note? Is too much comments in someone else's code hard to read? Does it cluster? Does too much grey death text give you a migraine? Are point the obvious comments rather annoying? // This is an if statement. // This is a while statement.

    Thoughts and comments, greatly appreciated. I'm gathering a bit of private research.

    Thank-you for your time.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Commenting your code: RIGHT or WRONG way?

    Javadoc is a MUST. You should always put javadocs in front of public methods and class declarations. There are also some valid arguments for putting them on private class variables and private methods. Javadocs are important because you can use them to automatically generate the API documents (like the ones you see on oracle's APIs), and you can use them to provide other developers with information when they are using the method or variable with one of those auto-complete suggestion popups that popular IDEs have.
    Single line statements for permanent commenting should only be used if something particularly complex is happening in the code. If it is simple code that a competent developer should be able to trace and understand by looking at it, it should not be heavily commented. But if it is complex and you have many loops and condition statements, a few comments here and there can be very helpful to understand what the code does.
    Notice how I said "permanent" comments. There are also temporary comments which are tagged. These tags are used to indicate future plans to the code, and most IDEs will notice them and list them for you from a project level so you can find them easily.

    Here is an example of the javadoc and tagged comments:
    /**
     * This class is an example, and this is a class javadoc. 
     * Notice the double stars on the first line. A single star is a comment block.
     * A double star is a javadoc.
     *
     * @author John Smith
     * @date 1/9/2013
     */
    public class Foo {
     
    	/**
    	 * This is a variable javadoc.
    	 */
    	public int var;
     
    	/**
    	 * This is a method javadoc.
    	 * This method returns an integer.
    	 * 
    	 * @return the integer 5
    	 */
    	public int returnSomeInt() {
    		return 5;
    		// TODO: change to return 1. The todo tag indicates future plans (notice all capitals)
    	}
     
    	/**
    	 * This method is just here to show the other tags
    	 */
    	public void someOtherMethod() {
    		// FIXME: This tag is used to indicate a known bug which should be fixed. You should briefly state the problem and a solution if you have one planned
    		// XXX: This is just a general notification for the developer, which are neither todos or fixmes
    	}
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Commenting your code: RIGHT or WRONG way?

    So my development process actually starts with comments. I begin by describing what it is I need to do and roughly how it should get done. Filling in the actual code comes second.

    Adding extra comments and modifying the base comments comes as needed. The million dollar question is does this new comment make my code more clear to others months or even years from now?

    There are such things as wasted comments. In general I find these comments to be those which merely repeat what a single isolated line of code does:
    // some wasteful comments:
     
    // increment i
    ++i;
    // add a and b
    c = a + b;
     
    // compute the dot product of v1 and v2
    val = v1.dot(v2);
     
    // is some_condition true?
    if(some_condition == true)
    {
    }
    // otherwise,
    else
    {
    }

    In general comments should explain the context, or if you have a complicated expression explaining it in plain English may also be warranted. Here are some reasonable comments (note: even though the comments may be reasonable, the actual code isn't necessarily good):
    // compute the dot product of v1 and v2
    val = v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
     
    // swap A and B
    int tmp = A;
    A = B;
    B = tmp;
     
    // Creates a new JButton with some text using reflection
    JButton.class.getConstructor(String.class).newInstance("A Button");

    Here's an example of how I might develop a sort method.

    sort_start is where I would start from, writing out comments and having very minimal actual code. sort_impl is the finished implementation with appropriate comments. Yes, I am missing all of the Javadocs. Ignore that and follow Aussiemcgr's advice on always having Javadoc.

    public void sort_start(int[] data)
    {
        // A simple selection sort.
        // for every index in data:
            // find the max value between [index, length)
            // swap the max value with the value at index
    }
     
    public void sort_impl(int[] data)
    {
        // A simple selection sort.
        for(int i = 0; i < data.length; ++i)
        {
            // find the max value between [index, length)
            int max_idx = i;
            for(int j = i; j < data.length; ++j)
            {
                if(data[j] > data[max_idx])
                {
                    // found a new max value
                    max_idx = j;
                }
            }
            // swap the max value with the value at index
            int tmp = data[j];
            data[j] = data[max_idx];
            data[max_idx] = tmp;
    }

  4. #4
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Commenting your code: RIGHT or WRONG way?

    Personally, I comment on why my code does something, not how it does it. My rationalization is that if the how isn't immediately obvious to another coder then I need to refactor for readability. Code should explain what code does. The why is more important for maintainers and can rarely be expressed without an explanation. I find comments like 'increase i by 1' for an i++ to be a sign of inexperience or lack of confidence in their code. It adds no value to readability or maintainability.

    Oh, and Javadocs. Absolutely essential for API's or libraries. Don't even start implementing an API without javadoc declarations. It's also a very good idea for public classes and methods however I've found in my latest job working on a rather complex android app we prefer to 'F3' open declaration than look at the context information so it's a very low priority to javadoc. I'm also a little old school with javadocs in that I like to state the preconditions, preconditions and big-o if applicable. It's not very common but I like it because down the road it gives me the context of the method.

    HelloWorld's method is brilliant for algorithm design. If I have some rather complicated logic I will start with pseudo-code comment and commit it to version control. As I implement the logic I'll remove the useless comments.

  5. #5
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Commenting your code: RIGHT or WRONG way?

    I personally hate useless comments or comments which state the obvious. If your comments look like these:
    	/**
    	 * Sets the name of this object to someName.
    	 */
    	public void setName(String someName) {
    	}
    Then better remove the comment entirely to save some place. This is really not going to help anybody.


    What I would advice you is to say what kind of exceptions a method could throw, what the valid return values might be, what should / should not be given as an argument, etc.

    Example:
    	/**
    	 * Returns the important data that is somehow connected to the given integer and string arguments.
    	 * 
    	 * anInteger should be within the range [0, getSize()) otherwise an OutOfBoundsException will be thrown.
    	 * someParam should not be null, otherwise a NullPointerException will be thrown.
    	 * 
    	 * The returned List can be null unless the method "initialize()" has been invoked beforehand.
    	 */
    	public List<?> getImportantData(int anInteger, String someParam) {
    	}
    Thats not a perfect example, but I hope it gets the point across. These information can be really helpful for other programmers when using your method.


    I usually use single line comments to comment code in a complex method to help myself rewrite the method later on if the need arises.
    For example, I write loop invariants at the beginning of a loop body.
    Or in complex nested if-then-else branches I write a "label" for each situation at the beginning of the code blocks.
    Or when 2 method calls need to be invoked in a particular order or otherwise the program will crash I will write that too. Just in case I might, at some point, decide to switch them around.
    		for (int i = 0; i < newSize; i++) {
    			for (int j = i; j > oldSize; j *= 2) {
     
    				// newSize > oldSize
    				// i > oldSize && j > oldSize
     
    				doSomething(i, j);
    			}
    		}
     
    		// doInitialization must always be called before doAction or a NullPointerException will be thrown!
    		doInitialization();
    		doAction();

    This is not the greatest example either, but maybe you get the point:
    		if (mouseWithinWindow()) {
    			if (mouseIsLeftclick) {
    				// User clicked inside of window; update window components to react to user input
    			} else if (mouseIsRightclick()) {
    				// User rightclicked window; hide the window and open information screen
    			}
    		} else {
    			if (mouseIsLeftclick()) {
    				// User clicked outside of window; move window to this position
    			}
    		}
    In general, I would prefer to not use large if-then-else constructs to control the logic behind an application, but for a fast prototype it might be okay.

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Commenting your code: RIGHT or WRONG way?

    I personally hate useless comments or comments which state the obvious. If your comments look like these:

    /**
    * Sets the name of this object to someName.
    */
    public void setName(String someName) {
    }

    Then better remove the comment entirely to save some place. This is really not going to help anybody.
    The comment itself if poorly written. But this comment is actually a javadoc, so it is important to include. In fact, it should also have a param tag which describes the purpose of the someName variable. Javadocs can sometimes feel unnecessary for setters and getters, but it is a coding standard because it allows the generation of the API. A developer who is using an API should not have to attempt to guess the purpose of a method, or trace a method, to understand what it does. That information should be clearly stated with javadocs. You can view all the javadoc standards here (there is a lot): How to Write Doc Comments for the Javadoc Tool
    Your second example, is a bit better, but you left out the javadoc tags, which makes the javadocs format better when they are generated:
    	/**
    	 * Returns the important data that is somehow connected to the given integer and string arguments.
    	 * 
    	 * @param anInteger should be within the range [0, getSize()) otherwise an {@link IndexOutOfBoundsException} will be thrown
    	 * @param someParam should not be null, otherwise a {@link NullPointerException} will be thrown
    	 * 
    	 * @return a List which contains the important data. The list can be null, unless the method {@link #initialize()} has been invoked beforehand.
    	 */
    	public List<?> getImportantData(int anInteger, String someParam) {
    	}

    Also, with regard to HelloWorld's example. This is a good example where you could also include the TODO tag, since the comments are indicating future plans:
    public void sort_start(int[] data)
    {
        // TODO: A simple selection sort.
        // for every index in data:
            // find the max value between [index, length)
            // swap the max value with the value at index
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. What's wrong with my code?
    By shen in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 18th, 2013, 06:34 AM
  2. Overzealous Commenting?
    By OA-OD-JD1 in forum Java Theory & Questions
    Replies: 10
    Last Post: January 27th, 2012, 04:03 PM
  3. Commenting in Java
    By djl1990 in forum Java Theory & Questions
    Replies: 2
    Last Post: October 26th, 2011, 12:15 PM
  4. Why no emphasis on commenting
    By Norm in forum The Cafe
    Replies: 2
    Last Post: July 25th, 2011, 07:53 AM
  5. Mastermind commenting help needed! :)
    By Mahela in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 28th, 2011, 03:55 PM