Home Java Java-tips Flow If 'if' Statement - Indentation

Ask Questions?

View Latest Questions

Advertisement


 
 

'if' Statement - Indentation
Posted on: July 26, 2006 at 12:00 AM
Indent to make programs readable

Java Notes

'if' Statement - Indentation

Indent to make programs readable

There are several meathods to make programs readable. How can you easily make the reader see which statements are inside the true part and false part of an if statement.

The best way to show this is to indent the statements that are inside. To do this you move the statements to the right by a few spaces. People commonly use two, three, or four spaces. Choose one number (eg, I use 2 or 3), and use it for all programs.

Java doesn't care about your indentation -- it is for humans (including yourself!).

Example 1 - No indentation - BAD BAD BAD

Here is the paintComponent() method from a previous page without indentation. This is small, so it's easy to see which statements are in the true and false parts. If the if statement is much larger, it will be unreadable without indentation.
   public void paintComponent(Graphics g) {
   super.paintComponent(g);
   if (marks < 50)
   g.setColor(Color.red);
   else
   g.setColor(Color.black);
   g.drawString("Score = " + marks, 10, 50);
   }

Example 2 - No indentation and no line breaks

Even a very short method is almost unreadable when you take out the line breaks and spaces. Here is the same method:
public void paintComponent(Graphics g) {super.paintComponent(g);if (marks<50) g.setColor(Color.red);else g.setColor(Color.black);g.drawString("Score = " + marks,10,50);}
Copyleft 2003 Fred Swartz MIT License, Last update: 2001-09-16
Advertisement


DMCA.com