<p>Indentation can be used as a visual queue for processes. Whenever there is a bug in the code, it is possible to more easily spot it (again, visually, not just by understanding). Especially wrongly placed curly braces are easy to find this way.</p>

CC BY-SA 3.0
2017-07-13T18:57:36.490Z
I use an editor that auto-indents. If it indents wrong, then I first swear at it, then I realise that I made a mistake (missed a bracket or something).
ctrl-alt-delor
CC BY-SA 3.0
2017-06-15T16:37:02.470Z
2017-06-15T16:37:02.470Z
W. Vrielink
<p>It has taken me a long time to get to a point where my students regularly indent properly.  I basically use a 4-part strategy.  <em>(My work here in the context of AP Computer Science, so my examples are all in Java)</em></p>

<p>First, <em>right from the beginning</em>, and repeatedly, I talk about the two audiences for code: the computer <strong>and people</strong>.  These two audiences have completely different needs.  I come back to this theme with every new structure that I talk about, discussing coding style and norms with if statements, variable declarations (naming conventions), for loops (hey, why do we avoid break statements?), etc.</p>

<p>Second, I grade most of their labs right in front of them, code-interview style.  The first assignments are always quite simple, so I focus in on indentation, variable names, <em>vertical space<sup>1</sup></em>, and the four Cs: clarity, clarity, clarity, and clarity.  </p>

<p>I talk through the clarity of their code in depth and inflict outrageous penalties for unclear code, but allow them to go back and refactor for a better grade with no penalty.  Rinse, lather, and repeat (as needed).  The first lab is always painfully time-intensive to go through, but by lab 3 or 4, much of the code (and the grading!) is fast, smooth, and clear.</p>

<p>Third, I provide a few monstrous code examples throughout the year like this:</p>

<pre><code>int n = 17;
if (n &lt; 5)
if (n &gt; 10) System.out.print("A");
else System.out.print("B");
if (n &gt; 17)
if (n == 17) System.out.println("C");
else System.out.println("D");
else System.out.println("E");
</code></pre>

<p>It doesn't take a rocket scientist to figure out that poor indentation is the one and only reason that this code is so difficult to read and understand.  In case they miss it, I also reinforce this point verbally every time I give examples like this.</p>

<p>Fourth, the group work that I give requires them to have to provide code to each other, and make sense of what their peers have done.  Over time, they start enforcing norms on each other.</p>

<p><sup>1</sup> <strong>Vertical space</strong>, you ask?  Two reasons: first, because vertical space is used to separate ideas, like paragraphs, and second, because the very <em>mention</em> of this problem in their code shocks students immediately into thinking about how <em>everything</em> that they write helps to serve clarity.</p>

CC BY-SA 4.0
2020-09-15T16:15:38.743Z
Do you think break should always be avoided? Sometimes the clearest exit point from the loop is in the middle, or there are two exit conditions - I find that break can be very clear in these situations.
composerMike
CC BY-SA 4.0
2020-09-16T11:58:04.570Z
@composerMike Largely, yes, but not always.  If it's part of the core, logical flow of the loop, then the loop should be structured to make the intention clear in the first place. If it's for exceptions, however, then breaks can make sense.  One litmus test I use when explaining a loop header to students is, "if the inside contents of the loop were pages and pages long (so we couldn't, at a glance, find break statements, for instance), would your loop header still make obvious what's happening and why?" I recognize this is an extreme position. I even encourage meaningful variable (cont)
Ben I.
CC BY-SA 4.0
2020-09-16T11:58:42.727Z
(cont) names in loop headers if the loops aren't crystal clear on their own.
Ben I.
CC BY-SA 4.0
2020-10-04T06:50:02.183Z
@BenI. Extreme, maybe, but makes sense as a position for students. Just the other day one of my students wrote a break for core loop logic and I realized right away what you are talking about. I asked him to restructure the loop.
composerMike
CC BY-SA 4.0
2020-10-04T13:23:33.440Z
@composerMike Your comment just made my day!! 
Ben I.
CC BY-SA 3.0
2017-07-08T04:18:28.787Z
Introduce them to some examples from code golf
pojo-guy
CC BY-SA 3.0
2017-05-27T12:41:06.300Z
number four is in a way inter-student "community moderation" of code.
ItamarG3
CC BY-SA 3.0
2017-05-24T13:26:18.750Z
2018-03-28T19:42:13.500Z
2018-03-28T19:42:13.500Z
Ben I.
<p>Indentation is important so that you can see what code will be run based on the existing conditions.</p>

<p>So for a simple example, consider:</p>

<pre><code>for (x=0; x&lt;100; x++) {
    if (item % 2 == 0) {
         print x;
         print " is even";
    } else {
         print x;
         print " is odd";
    }
}
</code></pre>

<p>Looking at this code, without reading it I can see from the indentation alone, that all of the lines will be run during the <code>for</code> loop.  Without the indentation, I would have to search for matching <code>}</code>s.  That would be quite slow.  It also shows me that there is an <code>if</code> condition, and again, it shows me what lines will be run. </p>

<p>Without the indentation, the code is very hard to parse.  The longer the routine, the more difficult it will be.  Indentation is the key to manageability and maintainability.  Without indentation, it quickly becomes very hard to fix problems and add new features.</p>

<p>Here is unindented code.</p>

<pre><code>for (x=0; x&lt;100; x++) {
if (item % 2 == 0) {
print x;
print " is even";
} else {
print x;
print " is odd";
}
}
</code></pre>

<p>To me, it is very clear that I can not tell what is happening in that code. </p>

<p>I would teach it by examples like this.  You could also take unindented code on a slide and ask them to make a change to the code.  Then ask the same on another slide that has better indentation. They will quickly see the issue on their own.</p>

<p>As pointed out in a comment, do the same activity with a bug in the code.  Asking them to find the bug.  A great example to use for this is a missing or mismatched bracket.</p>

CC BY-SA 3.0
2017-05-24T13:33:35.790Z
Another example you could add would be asking the students to debug unindented code v. indented code.
thesecretmaster
CC BY-SA 3.0
2017-05-24T13:13:41.257Z
2018-03-28T20:47:26.777Z
2018-03-28T20:47:26.777Z
nycynik
<p>Lots of good comments here.  Showing bad code and asking them to understand it will particularly drive the point home.</p>

<p>I've taken to having coding standards in my courses.  No one followed them until there were points attached, of course.  Initially, it was protect my eyesight, but it helps the students write clearer code.  </p>

<p>I also have a couple exercises I do when students ask what the big deal is.</p>

<p><strong>Exercise 1:</strong></p>

<ol>
<li>Grab a book off my shelf in the office.</li>
<li>Open the book and hold it in front of them and count backwards from 3.  </li>
<li>Close the book and take in their bewildered look.</li>
<li>Ask them what they can tell me about what was on the pages of the
book.  Often they'll say "nothing," but then I ask, were there any figures, sections, pragraphs?</li>
<li>They'll start to say things like "there was a graph on the right hand page at the top, and ... 2 subsections."  Me:  Did the graph have a legend or title?  Them:  "Yes, sure, both."  Were there subsubsections?  Were they just single paragraphs?  You do need to a pick a book that isn't just pages of text, but most academic books work fine.  (You can cheat and look at the pages first to pick something that isn't a 2-page paragraph.)</li>
<li>Then I ask how they knew all this in just a few seconds.</li>
</ol>

<p>The take away is:  We use physical formatting to help the reader understand the structure of a document at a subconscious level --- you don't have to read it, and you can identify the components and key relationships almost instantly.  Then you can use your intellectual effort to understand what's there rather than "Is this one of the items that goes with that thing?"  Publishers have figured these things out and honed their skills for centuries.  Alas, self publishing and the web means there are a lot of poorly designed documents around.</p>

<p>For programming, you don't want anyone to use their conscious thought to answer easy things like "Is this statement controlled by a test in a conditional?  In a loop?  Is this a function call or a special syntactic thing?  How many arguments are there for this function?"  There are enough things you'll have to think hard about, and it's inconsiderate to make your reader spend their valuable time and energy on mundane items like this.  That reader might be you in 4 or 5 days even, when you've found a bug and can't quite remember what's going on in this part of the code.</p>

<p><strong>Exercise 2:</strong></p>

<p>Print out some code and then put it some distance away.  E. g., stand it up on the marker tray of a white board and back up until the text is too blurry to read.  I used to say 10 feet, but my eyes are bad enough now I can just take my glasses off.  Just ask the students when they can't really read most of the words.  </p>

<p>If the code is formatted in a way that is considerate of a human reader, we can tell how many functions there are, which functions have loops, which have nested conditionals, all without reading any text at all.  We can even pick out the more complicated functions and sometimes even spot opportunities for refactoring based on common shapes!</p>

<p>Side note:  I had a blind student once who was a fantastic programmer.  I hired him as a TA, and he was superb at that, too.  He was once hanging out around my office when I was talking to a student about these things, and he blurted out "I don't know why you people need that stuff!  It's just 'space, space, space, space,...' and it's annoying."  It's true:  he takes in programs in a necessarily linear way, and he makes structures in his head that I cannot fathom.  I program, and teach my seeing students to program, by drawing lots of pictures.  I have no idea what he has in his mind, but it sure works!  I wish I knew how he did it.</p>

CC BY-SA 3.0
2017-06-15T01:25:30.067Z
I love your two exercises. It's a very clever illustration of the gains!
Ben I.
CC BY-SA 4.0
2021-01-27T13:39:48.310Z
Really cool "proofs"! I suppose you could do the second one in an online format by taking an image of code and applying some blurring effects to it.
ObscureOwl
CC BY-SA 3.0
2017-06-15T00:01:40.400Z
2017-06-15T00:01:40.400Z
user3329809
<p>Indentation (in most languages) is just for readability.  This aids in maintainability and other good stuff, all of which an intro student is completely unaware of or uninterested in.</p>

<p>So it is best taught by making the student read code they have not written.  (e.g. what does this code do?, etc.)  Show them some sufficiently complex, badly formatted examples (maybe even under quiz time pressure), and let them discover for themselves that well formatted (indented) code is much easier to read and understand.</p>

<p>Then they will likely be a bit more interested in your description of good code formatting practices.</p>

CC BY-SA 3.0
2018-03-29T17:35:10.920Z
I really like the idea of having them trace messy code. Might have to try that next year.
Ryan Nutt
CC BY-SA 3.0
2017-06-07T17:42:59.260Z
This applies not only to indentation, but also to issues such as naming and comments.
Chris Okasaki
CC BY-SA 3.0
2017-05-24T20:54:26.277Z
2017-06-07T03:47:11.330Z
2017-06-07T03:47:11.330Z
hotpaw2
<h2>A quick exercise</h2>
<ol>
<li><p>Write the most garbled code of your life (I know, I feel your pain) - terrible variable/function names, no indentation, code-golfed lines here and there, weird tricks, no comments, and so on.</p>
</li>
<li><p>Insert a small, barely-noticeable-in-good-code error.</p>
</li>
<li><p>Ask your students to find the error. (If you wish, tell them that this exercise is graded as motivation, or whatever.)</p>
</li>
<li><p>Go out for lunch, play a couple games of Monopoly, do some work on that coding project....then come back. Ask who has found the error. Ask why no  one has found the error. They will probably say that the code is terrible and hideous and convoluted.</p>
</li>
<li><p>Show them the same piece of code beautified - good variable/function names, indention, no code-golfing, comments, etc. Ask them to find the same error.</p>
</li>
<li><p>Explain the exact differences - i.e., the exact things you did to make the code hideous/good.</p>
</li>
<li><p>Admonish them to always do things the right way and use indentation or else they will go blind from terror and agony at a young age.</p>
</li>
</ol>
<h2>A language solution</h2>
<p>Force them to use Python for a few months. Never will you need to worry again.</p>
<h2>A more painful exercise</h2>
<p>Give students a longer term project. Let them indent or not indent to their hearts content. Say you don't care. Then listen to the whining from the students about how they don't know what they meant to do and that they need to start over because they didn't finish the project in one sitting. Step in from on high and explain the wonders of indentation again.</p>

CC BY-SA 3.0
2017-06-17T15:39:28.470Z
2017-06-17T15:39:28.470Z
2020-06-18T08:36:57.023Z
auden
<p>The purpose of indentation (to express the intended control flow) and the value are subtly different things. For a 5 line script, there is really not much value in indentation or comments - the code is a throw-away.</p>

<p>The real value in cleanly presented code (of which indentation is only a part) comes when a person is reading the code some time after it was written. Maybe it's something you've posted on SO as part of a question, maybe you're asking for help in improving the code from someone else (or explaining how good your code is). Maybe even worse your code is broken and you need to fix it in a hurry.</p>

<p>Well-presented code:</p>

<ul>
<li>Shows you care about the code and put some effort in to writing it</li>
<li>Makes your design intent more clearly visible</li>
<li>Helps typographical mistakes stand out</li>
</ul>

<p>It may be a hassle (is this an argument for better editors), but the time spent in keeping the code tidy usually pays off by both avoiding and finding bugs faster. Its a different (but related) question to 'would you prefer your code to be really fancy and efficient, or to work properly'? I think this latter problem is maybe easier to explain because it's more tangible.</p>

CC BY-SA 3.0
2017-07-08T04:24:40.760Z
with modern editors, keeping the code tidy, to the minimum standards of the language's preferred style book, is usually two keystrokes.
pojo-guy
CC BY-SA 3.0
2017-05-24T17:05:21.993Z
Given the audience, it shouldn't be necessary to ask for explanations of down-votes. Have I upset someone already?
Sean Houlihane
CC BY-SA 3.0
2017-05-24T13:51:55.883Z
2017-05-24T13:51:55.883Z
Sean Houlihane
<p>I think the student's response, "because it's a hassle", is interesting and worth a little more thought. When I am helping students in our Computer Center, I'm amazed at how difficult their code is for me to read, often because of indentation. </p>

<p>Since our IDE automatically provides indentation (and the programmer's text editor that student can use does as well), I can't for the life of me figure out how students are even able to enter code without correct indentation; during lecture, when I type some examples of poorly formatted code, it is quite a bit of work to stop the editor from automatically formatting it.</p>

<p>The only two things I've actually seen cause this are:</p>

<ul>
<li>Copy and paste from another part of the code or from an email or discussion post where the original was not formatted.</li>
<li>Using the space bar instead of the tab key when tabs are needed.</li>
</ul>

<p>Even then, it seems that students must do a lot of extra work to end up with non-indented code. I'd like to hear about what other instructors have observed.</p>

CC BY-SA 3.0
2018-04-02T02:54:18.383Z
Had one student that tried the "all on one line of text".  I reformatted it in Netbeans, graded it by inserting /* comments like this */ and re-reformatted it back all onto one line and returned it.
ivanivan
CC BY-SA 4.0
2020-01-20T19:23:41.950Z
Agreed that in the context where I teach, massively non-indented code is usually a sign of code copied from another source.
Daniel R. Collins
CC BY-SA 4.0
2021-01-27T13:50:37.930Z
We shouldn't underestimate the amount of heavy lifting IDEs do for us. But powerful IDEs can be intimidating and maybe we should do more to encourage students to adopt them.
ObscureOwl
CC BY-SA 3.0
2017-07-13T21:14:44.060Z
2017-07-13T21:14:44.060Z
Stephen Gilbert
<ul>
<li>indentation

<ul>
<li>value

<ul>
<li>shows grouping</li>
<li>makes code easier to read</li>
</ul></li>
<li>see also

<ul>
<li>paragraphing</li>
<li>good symbol names (variables and methods)</li>
</ul></li>
<li>related subjects

<ul>
<li>literacy / English</li>
</ul></li>
<li>is like

<ul>
<li>bullet lists</li>
<li>poetry</li>
</ul></li>
</ul></li>
</ul>

CC BY-SA 3.0
2017-07-13T18:55:55.513Z
2017-07-13T18:55:55.513Z
ctrl-alt-delor
<p>I did some debugging with year 10 students in Python and put some logical errors in there, so that they could see that the code had to be indented to run properly and achieve the correct result. I've also used a visualiser to show that if the code isn't indented properly, that it won't run correctly and complete as expected.</p>

<p><a href="http://www.pythontutor.com/visualize.html#mode=edit" rel="nofollow noreferrer">http://www.pythontutor.com/visualize.html#mode=edit</a></p>

CC BY-SA 3.0
2017-06-15T11:38:26.403Z
2017-06-15T11:38:26.403Z
Simon Hedges
<p>Like most things in CS, learning the 'why' of good code formatting is a gradual process. In CS1 and CS2 we mostly say "just do it or else you lose points". (I do go on to gently explain to them that I want to give them the most partial credit possible and that I can't do that if I can't read their code. They usually get the hint.)</p>

<p>Enforcing those good practices early, even under threat of penalty, pays off in their junior and senior years. That's when the understanding part kicks in -- when they're working on larger projects, sometimes with others.</p>

<p>When your juniors are critiquing the formatting of sample code from a visiting professor you know you're getting through. :)</p>

<p>Using an IDE like Eclipse (which can do 80-90% of the formatting for you) and a tool like Checkstyle helps tremendously. It's not a substitute for understanding why we do it, but it makes it less of a hassle for the stubborn students.</p>

CC BY-SA 3.0
2017-06-07T14:30:07.503Z
I disagree with the first part. Understanding that it makes code understandable to other humans is, in my opinion, essential.
ItamarG3
CC BY-SA 3.0
2017-06-08T00:07:43.573Z
I agree it's essential, but not that they have to get it right away. Most of my CS1 students only care about what they have to do to get an A (or B, or C...) so the best I can do is frame it in terms of *me* (the one grading their work) being able to read it. Their experience of software development just isn't mature enough to understand the collaborative aspect.
Lewis Baumstark
CC BY-SA 3.0
2017-06-07T14:22:00.510Z
2017-06-07T14:22:00.510Z
Lewis Baumstark
<p>Sometimes early students will just have trouble with this. there doesn't have to be pressure to get this all right at the beginning. by the second semester maybe, but at the beginning they should mainly just focus on writing code that works. but you can model good indentation to show them how much cleaer it is and they should pick it up naturally over time. </p>

CC BY-SA 3.0
2017-06-14T21:54:24.267Z
2017-06-14T21:54:24.267Z
Mr. Bamboozle
<p>I'm trying to teach why indentation is important, but the student doesn't indent. I asked why he doesn't indent, then he answered "That's because it’s a hassle."
It's OK to say "you should indent", but I want him to understand why indentation is important.</p>

<p>How do you teach why indentation is important?</p>

CC BY-SA 3.0
2018-03-29T01:52:22.480Z
Introduce them to the Obfuscated C contest, and ask them to debug the programs.  Since editors will fix indentation now, show them "Ctrl + Shift + F". Unless you're doing python, it's something that programmers don't worry about, they let the editor do it for them. My son (7 years old) has just started learning Java, and once he discovered the magic key strokes in Eclipse all was good
pojo-guy
CC BY-SA 4.0
2018-05-20T07:41:50.027Z
Why is it a hassle? Don't they use editors that indent automatically?
Barmar
CC BY-SA 3.0
2017-05-24T13:24:24.873Z
How large are the programs that are being written? If they were 5-10 lines, I can understand why he'd say that, and giving a longer task to complete might help to make him realise the value of indentation. The answer depends on the length, I suspect, and without that, it's hard to really address the problem.
Aurora0001
CC BY-SA 3.0
2017-05-24T13:52:39.467Z
On April 1st, provide all code examples in Code-Golf'd form, telling the students that you've realized the sublime elegance of short code.
Nat
CC BY-SA 3.0
2017-05-25T01:30:51.630Z
@Nat I'm going to have to steal your April 1st idea. That's great.
Ryan Nutt
CC BY-SA 3.0
2017-05-25T17:38:20.770Z
@nat When I was a software engineer, I had a colleague that argued against good-names (for methods and variables). I could not convince him, so issued a new rule, all names should be as short as possible (a, b, c … z, aa, ab …). At this point he agreed to at least give it a go.
ctrl-alt-delor
CC BY-SA 3.0
2017-05-26T12:58:39.507Z
One virtue of Python is that it requires proper indentation.  The students quickly see the benefit of good formatting habits.  These habits stick when they program in other languages.
ncmathsadist
<coding-style>
How to teach the importance of indentation
# How to teach the importance of indentation

(Asked by: username_0 on 2017-05-24)

I'm trying to teach why indentation is important, but the student doesn't indent. I asked why he doesn't indent, then he answered "That's because it’s a hassle."
It's OK to say "you should indent", but I want him to understand why indentation is important.

How do you teach why indentation is important?

**Tags:** coding-style

> **Comments:**
> **username_3**: How large are the programs that are being written? If they were 5-10 lines, I can understand why he'd say that, and giving a longer task to complete might help to make him realise the value of indentation. The answer depends on the length, I suspect, and without that, it's hard to really address the problem.  
> **username_4**: On April 1st, provide all code examples in Code-Golf'd form, telling the students that you've realized the sublime elegance of short code.  
> **username_5**: @username_4 I'm going to have to steal your April 1st idea. That's great.  
> **username_6**: @nat When I was a software engineer, I had a colleague that argued against good-names (for methods and variables). I could not convince him, so issued a new rule, all names should be as short as possible (a, b, c … z, aa, ab …). At this point he agreed to at least give it a go.  
> **username_7**: One virtue of Python is that it requires proper indentation.  The students quickly see the benefit of good formatting habits.  These habits stick when they program in other languages.  
> **username_1**: Introduce them to the Obfuscated C contest, and ask them to debug the programs.  Since editors will fix indentation now, show them "Ctrl + Shift + F". Unless you're doing python, it's something that programmers don't worry about, they let the editor do it for them. My son (7 years old) has just started learning Java, and once he discovered the magic key strokes in Eclipse all was good  
> **username_2**: Why is it a hassle? Don't they use editors that indent automatically?  

---

## 12 answers

### Answer by username_9 on 2017-05-24. Score: 41 | Accepted answer

It has taken me a long time to get to a point where my students regularly indent properly.  I basically use a 4-part strategy.  (My work here in the context of AP Computer Science, so my examples are all in Java)
First, right from the beginning, and repeatedly, I talk about the two audiences for code: the computer and people.  These two audiences have completely different needs.  I come back to this theme with every new structure that I talk about, discussing coding style and norms with if statements, variable declarations (naming conventions), for loops (hey, why do we avoid break statements?), etc.
Second, I grade most of their labs right in front of them, code-interview style.  The first assignments are always quite simple, so I focus in on indentation, variable names, vertical space1, and the four Cs: clarity, clarity, clarity, and clarity.  
I talk through the clarity of their code in depth and inflict outrageous penalties for unclear code, but allow them to go back and refactor for a better grade with no penalty.  Rinse, lather, and repeat (as needed).  The first lab is always painfully time-intensive to go through, but by lab 3 or 4, much of the code (and the grading!) is fast, smooth, and clear.
Third, I provide a few monstrous code examples throughout the year like this:
int n = 17;
if (n < 5)
if (n > 10) System.out.print("A");
else System.out.print("B");
if (n > 17)
if (n == 17) System.out.println("C");
else System.out.println("D");
else System.out.println("E");

It doesn't take a rocket scientist to figure out that poor indentation is the one and only reason that this code is so difficult to read and understand.  In case they miss it, I also reinforce this point verbally every time I give examples like this.
Fourth, the group work that I give requires them to have to provide code to each other, and make sense of what their peers have done.  Over time, they start enforcing norms on each other.
1 Vertical space, you ask?  Two reasons: first, because vertical space is used to separate ideas, like paragraphs, and second, because the very mention of this problem in their code shocks students immediately into thinking about how everything that they write helps to serve clarity.

> **Comments:**
> **username_11**: number four is in a way inter-student "community moderation" of code.  
> **username_1**: Introduce them to some examples from code golf  
> **username_10**: Do you think break should always be avoided? Sometimes the clearest exit point from the loop is in the middle, or there are two exit conditions - I find that break can be very clear in these situations.  
> **username_9**: @username_10 Largely, yes, but not always.  If it's part of the core, logical flow of the loop, then the loop should be structured to make the intention clear in the first place. If it's for exceptions, however, then breaks can make sense.  One litmus test I use when explaining a loop header to students is, "if the inside contents of the loop were pages and pages long (so we couldn't, at a glance, find break statements, for instance), would your loop header still make obvious what's happening and why?" I recognize this is an extreme position. I even encourage meaningful variable (cont)  
> **username_9**: (cont) names in loop headers if the loops aren't crystal clear on their own.  
> **username_10**: @BenI. Extreme, maybe, but makes sense as a position for students. Just the other day one of my students wrote a break for core loop logic and I realized right away what you are talking about. I asked him to restructure the loop.  
> **username_9**: @username_10 Your comment just made my day!!   

---

### Answer by username_16 on 2017-05-24. Score: 17

Indentation (in most languages) is just for readability. This aids in maintainability and other good stuff, all of which an intro student is completely unaware of or uninterested in.

So it is best taught by making the student read code they have not written. (e.g. what does this code do?, etc.) Show them some sufficiently complex, badly formatted examples (maybe even under quiz time pressure), and let them discover for themselves that well formatted (indented) code is much easier to read and understand.

Then they will likely be a bit more interested in your description of good code formatting practices.

> **Comments:**
> **username_17**: This applies not only to indentation, but also to issues such as naming and comments.  
> **username_5**: I really like the idea of having them trace messy code. Might have to try that next year.  

---

### Answer by username_12 on 2017-05-24. Score: 9

Indentation is important so that you can see what code will be run based on the existing conditions.
So for a simple example, consider:
for (x=0; x<100; x++) {
    if (item % 2 == 0) {
         print x;
         print " is even";
    } else {
         print x;
         print " is odd";
    }
}

Looking at this code, without reading it I can see from the indentation alone, that all of the lines will be run during the for loop.  Without the indentation, I would have to search for matching }s.  That would be quite slow.  It also shows me that there is an if condition, and again, it shows me what lines will be run. 
Without the indentation, the code is very hard to parse.  The longer the routine, the more difficult it will be.  Indentation is the key to manageability and maintainability.  Without indentation, it quickly becomes very hard to fix problems and add new features.
Here is unindented code.
for (x=0; x<100; x++) {
if (item % 2 == 0) {
print x;
print " is even";
} else {
print x;
print " is odd";
}
}

To me, it is very clear that I can not tell what is happening in that code. 
I would teach it by examples like this.  You could also take unindented code on a slide and ask them to make a change to the code.  Then ask the same on another slide that has better indentation. They will quickly see the issue on their own.
As pointed out in a comment, do the same activity with a bug in the code.  Asking them to find the bug.  A great example to use for this is a missing or mismatched bracket.

> **Comments:**
> **username_13**: Another example you could add would be asking the students to debug unindented code v. indented code.  

---

### Answer by username_14 on 2017-06-15. Score: 9

Lots of good comments here. Showing bad code and asking them to understand it will particularly drive the point home.

I've taken to having coding standards in my courses. No one followed them until there were points attached, of course. Initially, it was protect my eyesight, but it helps the students write clearer code.

I also have a couple exercises I do when students ask what the big deal is.

**Exercise 1:**

1. Grab a book off my shelf in the office.
2. Open the book and hold it in front of them and count backwards from 3.
3. Close the book and take in their bewildered look.
4. Ask them what they can tell me about what was on the pages of the
   book. Often they'll say "nothing," but then I ask, were there any figures, sections, pragraphs?
5. They'll start to say things like "there was a graph on the right hand page at the top, and ... 2 subsections." Me: Did the graph have a legend or title? Them: "Yes, sure, both." Were there subsubsections? Were they just single paragraphs? You do need to a pick a book that isn't just pages of text, but most academic books work fine. (You can cheat and look at the pages first to pick something that isn't a 2-page paragraph.)
6. Then I ask how they knew all this in just a few seconds.

The take away is: We use physical formatting to help the reader understand the structure of a document at a subconscious level --- you don't have to read it, and you can identify the components and key relationships almost instantly. Then you can use your intellectual effort to understand what's there rather than "Is this one of the items that goes with that thing?" Publishers have figured these things out and honed their skills for centuries. Alas, self publishing and the web means there are a lot of poorly designed documents around.

For programming, you don't want anyone to use their conscious thought to answer easy things like "Is this statement controlled by a test in a conditional? In a loop? Is this a function call or a special syntactic thing? How many arguments are there for this function?" There are enough things you'll have to think hard about, and it's inconsiderate to make your reader spend their valuable time and energy on mundane items like this. That reader might be you in 4 or 5 days even, when you've found a bug and can't quite remember what's going on in this part of the code.

**Exercise 2:**

Print out some code and then put it some distance away. E. g., stand it up on the marker tray of a white board and back up until the text is too blurry to read. I used to say 10 feet, but my eyes are bad enough now I can just take my glasses off. Just ask the students when they can't really read most of the words.

If the code is formatted in a way that is considerate of a human reader, we can tell how many functions there are, which functions have loops, which have nested conditionals, all without reading any text at all. We can even pick out the more complicated functions and sometimes even spot opportunities for refactoring based on common shapes!

Side note: I had a blind student once who was a fantastic programmer. I hired him as a TA, and he was superb at that, too. He was once hanging out around my office when I was talking to a student about these things, and he blurted out "I don't know why you people need that stuff! It's just 'space, space, space, space,...' and it's annoying." It's true: he takes in programs in a necessarily linear way, and he makes structures in his head that I cannot fathom. I program, and teach my seeing students to program, by drawing lots of pictures. I have no idea what he has in his mind, but it sure works! I wish I knew how he did it.

> **Comments:**
> **username_9**: I love your two exercises. It's a very clever illustration of the gains!  
> **username_15**: Really cool "proofs"! I suppose you could do the second one in an online format by taking an image of code and applying some blurring effects to it.  

---

### Answer by username_18 on 2017-06-17. Score: 6

## A quick exercise

1. Write the most garbled code of your life (I know, I feel your pain) - terrible variable/function names, no indentation, code-golfed lines here and there, weird tricks, no comments, and so on.
2. Insert a small, barely-noticeable-in-good-code error.
3. Ask your students to find the error. (If you wish, tell them that this exercise is graded as motivation, or whatever.)
4. Go out for lunch, play a couple games of Monopoly, do some work on that coding project....then come back. Ask who has found the error. Ask why no one has found the error. They will probably say that the code is terrible and hideous and convoluted.
5. Show them the same piece of code beautified - good variable/function names, indention, no code-golfing, comments, etc. Ask them to find the same error.
6. Explain the exact differences - i.e., the exact things you did to make the code hideous/good.
7. Admonish them to always do things the right way and use indentation or else they will go blind from terror and agony at a young age.

## A language solution

Force them to use Python for a few months. Never will you need to worry again.

## A more painful exercise

Give students a longer term project. Let them indent or not indent to their hearts content. Say you don't care. Then listen to the whining from the students about how they don't know what they meant to do and that they need to start over because they didn't finish the project in one sitting. Step in from on high and explain the wonders of indentation again.


---

### Answer by username_19 on 2017-05-24. Score: 5

The purpose of indentation (to express the intended control flow) and the value are subtly different things. For a 5 line script, there is really not much value in indentation or comments - the code is a throw-away.

The real value in cleanly presented code (of which indentation is only a part) comes when a person is reading the code some time after it was written. Maybe it's something you've posted on SO as part of a question, maybe you're asking for help in improving the code from someone else (or explaining how good your code is). Maybe even worse your code is broken and you need to fix it in a hurry.

Well-presented code:

* Shows you care about the code and put some effort in to writing it
* Makes your design intent more clearly visible
* Helps typographical mistakes stand out

It may be a hassle (is this an argument for better editors), but the time spent in keeping the code tidy usually pays off by both avoiding and finding bugs faster. Its a different (but related) question to 'would you prefer your code to be really fancy and efficient, or to work properly'? I think this latter problem is maybe easier to explain because it's more tangible.

> **Comments:**
> **username_19**: Given the audience, it shouldn't be necessary to ask for explanations of down-votes. Have I upset someone already?  
> **username_1**: with modern editors, keeping the code tidy, to the minimum standards of the language's preferred style book, is usually two keystrokes.  

---

### Answer by username_20 on 2017-07-13. Score: 4

I think the student's response, "because it's a hassle", is interesting and worth a little more thought. When I am helping students in our Computer Center, I'm amazed at how difficult their code is for me to read, often because of indentation.

Since our IDE automatically provides indentation (and the programmer's text editor that student can use does as well), I can't for the life of me figure out how students are even able to enter code without correct indentation; during lecture, when I type some examples of poorly formatted code, it is quite a bit of work to stop the editor from automatically formatting it.

The only two things I've actually seen cause this are:

* Copy and paste from another part of the code or from an email or discussion post where the original was not formatted.
* Using the space bar instead of the tab key when tabs are needed.

Even then, it seems that students must do a lot of extra work to end up with non-indented code. I'd like to hear about what other instructors have observed.

> **Comments:**
> **username_21**: Had one student that tried the "all on one line of text".  I reformatted it in Netbeans, graded it by inserting /* comments like this */ and re-reformatted it back all onto one line and returned it.  
> **username_22**: Agreed that in the context where I teach, massively non-indented code is usually a sign of code copied from another source.  
> **username_15**: We shouldn't underestimate the amount of heavy lifting IDEs do for us. But powerful IDEs can be intimidating and maybe we should do more to encourage students to adopt them.  

---

### Answer by username_24 on 2017-06-07. Score: 4

Like most things in CS, learning the 'why' of good code formatting is a gradual process. In CS1 and CS2 we mostly say "just do it or else you lose points". (I do go on to gently explain to them that I want to give them the most partial credit possible and that I can't do that if I can't read their code. They usually get the hint.)

Enforcing those good practices early, even under threat of penalty, pays off in their junior and senior years. That's when the understanding part kicks in -- when they're working on larger projects, sometimes with others.

When your juniors are critiquing the formatting of sample code from a visiting professor you know you're getting through. :)

Using an IDE like Eclipse (which can do 80-90% of the formatting for you) and a tool like Checkstyle helps tremendously. It's not a substitute for understanding why we do it, but it makes it less of a hassle for the stubborn students.

> **Comments:**
> **username_11**: I disagree with the first part. Understanding that it makes code understandable to other humans is, in my opinion, essential.  
> **username_24**: I agree it's essential, but not that they have to get it right away. Most of my CS1 students only care about what they have to do to get an A (or B, or C...) so the best I can do is frame it in terms of *me* (the one grading their work) being able to read it. Their experience of software development just isn't mature enough to understand the collaborative aspect.  

---

### Answer by username_6 on 2017-07-13. Score: 3

* indentation
  + value
    - shows grouping
    - makes code easier to read
  + see also
    - paragraphing
    - good symbol names (variables and methods)
  + related subjects
    - literacy / English
  + is like
    - bullet lists
    - poetry


---

### Answer by username_23 on 2017-06-15. Score: 3

I did some debugging with year 10 students in Python and put some logical errors in there, so that they could see that the code had to be indented to run properly and achieve the correct result. I've also used a visualiser to show that if the code isn't indented properly, that it won't run correctly and complete as expected.

<http://www.pythontutor.com/visualize.html#mode=edit>


---

### Answer by username_25 on 2017-06-14. Score: 2

Sometimes early students will just have trouble with this. there doesn't have to be pressure to get this all right at the beginning. by the second semester maybe, but at the beginning they should mainly just focus on writing code that works. but you can model good indentation to show them how much cleaer it is and they should pick it up naturally over time.


---

### Answer by username_8 on 2017-06-15. Score: 1

Indentation can be used as a visual queue for processes. Whenever there is a bug in the code, it is possible to more easily spot it (again, visually, not just by understanding). Especially wrongly placed curly braces are easy to find this way.

> **Comments:**
> **username_6**: I use an editor that auto-indents. If it indents wrong, then I first swear at it, then I realise that I made a mistake (missed a bracket or something).  

---

