Question:
It is common to hear that it is important to keep 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?
In addition to 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 serves to keep the code easier to understand.
For example, look at 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 here's 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 code without indentation, what the human eye and brain see is just a soup of open and close braces, if
s, while
s, etc. and it's hard to know where things start and where they end. In badly indented code, it is even worse, as there is an extra mental effort in realizing that the suggested indentation is inadequate and understanding which one would be the correct one.
Ultimately, it all boils down to making the code easier for a human to read, not a machine.
In particular, look at these terrible 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, the z()
appears to be inside the if
, but it is outside. In the second case, the else
is in the inner if
, but it has been indented as if it were in the outer. In the third case, as the y()
line was commented out, z()
ended up piggybacking inside the 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 indent-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 from Scheme/Racket, where although the compiler doesn't need indentation when the code is correct, in case there is a compilation error it will use indentation to suggest where the most likely place for the error to have occurred. .