When programmers write code, they tend to stick to an indentation style which essentially makes the program easier to read. When programs get more complex, there are often a number of lines of code which contain loops within loops amongst other things. If all code was written starting at the left edge of the page for every line, it would quickly become unreadable. Take the following example:
import stanford.karel.*;
public class BeeperPickingKarel extends Karel {
public void run() {
move();
if (noBeepersPresent()) {
pickBeeper();
}
move();
}
{
Although this selection of code is relatively simple and with a bit of effort, is fairly readable, it is still recommended that you indent your code to make the blocks and other statements stand out. Indenting and adding more line breaks in the code above would produce the following:
import stanford.karel.*;
public class BeeperPickingKarel extends Karel {
public void run() {
move();
if (noBeepersPresent()) {
pickBeeper();
}
move();
}
{
In the example above you can see that lines 6,7 and 8 form a section of code and that 4 – 10 have code within and 3 – 11 wrap 4 – 10 within that.
Notice how the if condition statement has its statement tabbed in and notice that each section of code tabs in by 3 spaces. By matching up the closing curly brace of each block with its header, you make the code easier to read by humans.
Note the last few words of the last sentence said “read by humans”. This is all who indentation is for… it’s for us who read and write the code. The computer doesn’t care if there are line breaks or tabs included as long as the code is syntactically correct… but when it comes to debugging, it is you will need to read your code and choosing to indent your code makes it far easier to see what blocks relate to what and what blocks are embedded inside of other blocks.
There are various standards for indenting code although none are particularly mandatory. Java appears to use 3 or 4 spaces which looks to work quite well and make it readable.
Note also that the colours used are to help you distinguish errors. If you don’t close a comment or don’t open with a curly brace, the rest of the program changes colour which helps you to identify where the problem is. Java tends to use the colours above although I believe different languages might use slight variations.
Leave a Reply
You must be logged in to post a comment.