Question:
It is common to hear that it is important to keep the code indented, which is not a difficult task with the help of an IDE.
Excluding languages that enforce indentation, such as Python, why is it important to keep code indented? Is it just the merit of readability?
Besides the programmer, who reads the code is the compiler. Does it make any difference to him, in languages that do not require indentation, to process the code with good/bad/no indentation?
Answer:
It makes the code easier to understand.
For example, see this code without any indentation:
if (a) {
if (b) {
while (c) {
d();
}
} else if (e) {
f();
} else if (g) {
h();
}
} else if (i) {
while (j) {
k();
}
}
Now see the same code with a very bad indentation:
if (a) {
if (b)
{
while (c) {
d();
}
}
else
if (e)
{
f();
}
else if (g)
{
h();
}
} else
if (i) {
while (j) {
k();
}
}
And now the well-indented code:
if (a) {
if (b) {
while (c) {
d();
}
} else if (e) {
f();
} else if (g) {
h();
}
} else if (i) {
while (j) {
k();
}
}
Note that in well-indented code, it's much easier to see right away how the structures are nested. In the code without indentation, what the human eye and brain sees is just a soup of open and close braces, if
s, while
s, etc and it is difficult to know where things start and where they end. In the malindented code, it's even worse, as it takes extra mental effort to realize that the suggested indentation is inadequate and to figure out which one would be correct.
In short, it all boils down to making the code easier for a human, not a machine, to read.
In particular, look at these dire examples where the wrong indentation makes the instructions appear to be in the wrong place:
if (x)
y();
z();
if (a)
if (b)
c();
else
d();
if (x)
// y();
z();
In the first case, z()
appears to be inside if
, but outside. In the second case, the else
is in the inner if
, but it was indented as if it were in the outer one. In the third case, as the y()
was commented out, z()
ended up hitching a ride inside if
. These pathological cases are avoided if you always delimit the scope with curly braces (or the equivalent depending on the language) or use an indentation-sensitive language like Python.
For the compiler, indentation almost always doesn't matter. The main exception is obviously Python, where the compiler uses indentation to nest structures. Another exception I remember is Scheme/Racket, where although the compiler doesn't need indentation when the code is correct, in case there's a compilation error it will use the indentation to suggest where the error is most likely to have occurred. .