How to Write Comments for your code ?

Motivation

  • it is really difficult to understand a code without any comments since most of the time we as a developer working on code written by someone else , and if the other person or the team is following the best coding practices they will add comments that will basically improve the readability and maintainability of the code.

Lets get started

  • There are two types of comments , documentation Comments and Implementation Comments.

Documentation Comments :

  • This should show how we can use that class , interface or method

  • "/**↵" : by doing this it will generate the template for the documentation comments

  • Example

    /**
    * The Foo class is a silly example to illustrate documentation 
    * comments.
    */
    public class Foo { 
      /**
      * An integer to keep track of for fun.
      */
      private int count; 
      ... 
      /**
      * Increment a value by delta and return the new value. 
      *
      * @param  delta   the amount the value should be incremented by
      * @return         the post-incremented value
      */
     int increment(int delta) {
         ...
     }
    }
    

Always write the documentation comments for below mentioned scenarios

  • Classes and interfaces
  • Fields
  • Methods, including all input parameters and return values

Implementation Comments :

  • These comments are there for the internal working of the method.