Page 1 of 1

Improving the Readability of Your Code With Proper Indentation, Line Breaks, and Comments

#1 xor-logic  Icon User is offline

  • HAL9000 was an Apple product
  • member icon

Reputation: 128
  • View blog
  • Posts: 764
  • Joined: 04-February 10

Posted 17 February 2010 - 08:35 PM

*
POPULAR

Improving the Readability of Your Code With Proper Indentation, Line Breaks, and Comments


Preface:

If you are an experienced programmer, you can likely skip reading this. This is targeted towards new programmers who, as eager as they are to program the worlds best OS or desktop search app (spaghetti code baby), disregard the basics.


Intro:

Is this tutorial really necessary?
-Yes. A quick scan through posts on this site will provide numerous examples of code that are just absolutely impossible to read, either because they look like control of the tab key was delegated to a squirrel coming off a three day sugar binge, there is enough whitespace between lines to comfortably hold the Titanic, or they just forgot to communicate through comments what they were trying to do in a particular block of code, and possibly forgot themselves.


Do I really have to worry about readability? I mean, it's just a homework assignment/personal project? -Absolutely. Always bear in mind that no matter what you're writing, someone will probably be reading it eventually. Whether that is you, because you want to reuse the code or you're fixing a bug that magically appeared once you thought you were finished, or a teacher, or your peers both IRL and on coding forums like this. And especially if you want the world to see that you are 'totally teh most awesomest programmer in the world!!1!', it will help if they understand your code. It is hard to be impressed by something which you don't understand or can't read (or can't be BOTHERED to read).

Having (hopefully) made the case for readability, on we go:


Part 1 - Indentation:

If you know where to find the tab key on your keyboard, skip this paragraph. If you don't (and some people don't), you will in a minute. Look on the far left side of your keyboard. There is a key right above the Caps Lock key that should say something like "Tab", "->|", "|<- ->|" or some combination thereof. This is the tab key. Tapping this key will quickly add a predefined number of spaces in whatever you're writing (occasionally it's used for navigation, but that's a different tut).

Now you need to understand the other easy part of proper indentation: The Block. A block is a very easy thing. It's the code that is contained between an opening brace "{" and a closing brace "}". For example:
public static void main(String[] args) {
  //THIS IS A BLOCK
  //THIS IS A BLOCK
  //THIS IS A BLOCK
}

public void whatNot() {
  //THIS IS A BLOCK
  //THIS IS A BLOCK
  for(int i = 0; i < 5; i++) {
    //THIS IS ANOTHER BLOCK INSIDE THE FIRST
      if(x == 5) {
         //THIS IS A THIRD BLOCK.
      } //THIS ENDS THE THIRD BLOCK
  } //THIS ENDS THE SECOND BLOCK
} //AND THIS ENDS THE FIRST BLOCK




Note: Your tab key is the easiest to use for this, but if you feel it indents too far, feel free to substitute it with a few taps on the space bar. If you do though, always use the same number of spaces instead of one tab. So if you're using three spaces instead of one tab, and you should be indenting two tabs, you would use six spaces.

Now, on to indenting. When to indent is the easiest part of this whole thing. Start with zero indentation. Left justified. Smack against the left side of the screen. Then, for every opened block, you should be indenting one more unit (tab or a # of spaces). For every closed block, you should indent one less unit. Ex:
//start on the left side, no indents
public class Whatever {

  /*You just opened a block, so everything from 
  here to when you close the block needs to have
  at least one unit of indentation. */

  public static void main(String[] args) {

    /*You just opened another block, so you add 
    one more unit to however many you were         previously indenting by.  (Method     declarations will almost always be 
    indented by only one.)*/

    for(int i = 0; i < 5; i++) {
      /*You've opened a third block, so you
      should be indenting three units. */

      System.out.println(i);
    }
     
    /*You've closed the third block now, so 
     we're back to using two units. */

    x += 5;
    y = x;
    
  }
  /*That closes the second block, so now back
    down to indenting one. */

  public void whatNot() {
  }

}



Generally, the closing brace with which you close a block shares the same indentation as the line where you opened the block with an opening brace.


Part 2 - Line Breaks:

Single line breaks: These are generated by tapping the enter key. You know how to use these.

Double line breaks: These can be used to separate parts of your code that are logically different, or are not related to the part that immediately comes before it.

Think back to paragraph spacing in English class. Generally, a new train of thought belongs in a new paragraph.

For example, the main code of a method should be separated from the variable declarations of that method by double line breaks. Methods should have two line breaks between them.

You do not need to use double line breaks after the opening brace of a method or before the closing brace, however it's not really frowned upon either, so it comes down to a matter of personal taste.

Triple line breaks: These could be used on a rare occasion when you NEED to indicate an extreme logical separation between one bit of code and another, but for the most part, DO NOT USE THEM.

Four line breaks or more: No, no, NO! But what about...? No. But I need to...? Definitely not.

public class Whatever {
   //double break to separate method from class
   public static void main(String[] args) {
      int a = 1;
      int b = 2;
      int c = 0;
      //actual code is logically different from variable declarations
      c = a+b;
      System.out.println(a + "+" + b + "=");
   }
   //double space between methods
   public void whatNot() {
   }
}




Part 3 - Comments:

Comments are created thusly: to create a single line comment, use "//". Everything on the line following that symbol will be shown and treated as a comment.

If your comments need to take more than one line, you can either use multiple single-line comments, or sandwich your comment between "/*" and "*/". Again, everything between those is shown and treated as a comment.

//This is a single-line comment.

/*This is a 
multiple-line
comment.*/

/*So
*is
*this.*/



If the purpose of a bit of code is NOT immediately obvious, it probably should be commented. Keep your comments on point, use good English (or whatever language is used by your probable readers), and keep it brief.

Also, on a larger scale, it is sometimes helpful to comment a method or a larger section of code and explain briefly what you are trying to accomplish with it.

If the purpose of a line of code is immediately obvious (i.e.: a variable declaration) you do not need to comment it. However, you may wish to do so if you want to explain what that variable will be used for.

Comments should PREFACE what they explain, meaning they should be before it. A single line break should be used between a comment and the code it explains.


Closing:
Your code should be looking better if you follow these guidelines. One last thing though. If you update or revise your code, do it neatly and cleanly. Floating fragments of code long since departed do nothing to improve the appearance of your program.

Is This A Good Question/Topic? 6
  • +

Replies To: Improving the Readability of Your Code

#2 pdkharkar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 345
  • Joined: 19-January 09

Posted 19 February 2010 - 03:42 AM

Thanks for that
Nice tutorial
I knew about the indentation but did not know about the logical sections and double triple line breaks
thanks for that
Was This Post Helpful? 0
  • +
  • -

#3 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3120
  • View blog
  • Posts: 19,163
  • Joined: 14-September 07

Posted 19 February 2010 - 12:35 PM

I had a teacher that always copy/pasted our code into notepad to see if we indented correctly. The idea was that you won't know what program a prospective employer would use to open your code, so you want it to be as clean/formatted as possible.
Was This Post Helpful? 2
  • +
  • -

#4 MacWilliam  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 03-November 08

Posted 18 March 2011 - 05:26 PM

If this can be helpful, here is the type of comments which can be useful to give some guidance for other programmers.
Try to be as explicit as possible. If you use JavaDocs with NetBeans, documenting your code in this fashion will make your work look very professional.

/**
 *This a PatientManager that manages Patients for the Pre-Operation Project;
 * <p>
 * The {@code PatientManager} class implements a Manager to look after Patients. To
 * use this calls you might do the following</p>
 * <p> Examples of expected usage:
 *
 * <blockquote><pre>
 *      PatientBean pb = new PatientBean();
 *      // now add a Patient
 *      PatientBean.addPatient();
 * </pre></blockquote>
 * <p>
 * This would add all the required information for a single patient
 * This Patient is referenced by the unique Identifier patientId.
 * </p>
 * Created on : Feb 28th 2010
 * @author MacWilliam
 * @version 1.0
 * @since JDK1.5
 */


Was This Post Helpful? 0
  • +
  • -

#5 milawynsrealm  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 23
  • Joined: 12-May 11

Posted 23 June 2011 - 09:23 PM

Commenting code is very important (enough programming book authors have made this statement crystal clear). As the program gets larger in size, you or someone else will eventually have to go back to existing and make changes to it. And code with lack of proper comments will be harder to read and determine it's actual function. For example:

//example #1:
int hsAdd(int value);

//example #2:
//Adds/subtracts value to the high score table, then returns the final value
int hsAdd(int value);



Which is easier to read?
Was This Post Helpful? 0
  • +
  • -

#6 Brewer  Icon User is offline

  • Awesome
  • member icon

Reputation: 179
  • View blog
  • Posts: 1,044
  • Joined: 14-June 10

Posted 03 July 2011 - 12:40 PM

Nice tutorial. In part 3 (Comments), you say that a comment can be created by using '//'. I just want to point out that this is not always the case. For example, in Python, we make comments using a hash symbol (#).
Was This Post Helpful? 0
  • +
  • -

#7 xor-logic  Icon User is offline

  • HAL9000 was an Apple product
  • member icon

Reputation: 128
  • View blog
  • Posts: 764
  • Joined: 04-February 10

Posted 04 July 2011 - 01:00 AM

Brewer, this tut was originally written for, and posted to, the Java tuts. It was one of the mods who decided that it should be moved to Software Development. While I'm definitely not complaining about it being in a more visible position, it does render certain things I wrote incomplete, as again, it's all from a Java perspective. :D
Was This Post Helpful? 0
  • +
  • -

#8 jackrowe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 07-November 11

Posted 07 November 2011 - 12:47 PM

Function names are an important method of commenting; I sacrifice typing ease to function-name-verbosity, then refactor code until middle- and higher-level functions can be read as if in English, often with function names alone. Cutting-and-pasting covers typing ease and ensures proper spelling.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1