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?

  • 2
    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 May 24 '17 at 13:24
  • 18
    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 May 24 '17 at 13:52
  • @Nat I'm going to have to steal your April 1st idea. That's great. – Ryan Nutt May 25 '17 at 1:30
  • @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 May 25 '17 at 17:38
  • 8
    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 May 26 '17 at 12:58

13 Answers 13

up vote 34 down vote accepted

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.

  • 1
    number four is in a way inter-student "community moderation" of code. – ItamarG3 May 27 '17 at 12:41
  • Introduce them to some examples from code golf – pojo-guy Jul 8 '17 at 4:18

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.

  • 3
    This applies not only to indentation, but also to issues such as naming and comments. – Chris Okasaki Jun 7 '17 at 17:42
  • I really like the idea of having them trace messy code. Might have to try that next year. – Ryan Nutt Mar 29 at 17:35

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.

  • 6
    Another example you could add would be asking the students to debug unindented code v. indented code. – thesecretmaster May 24 '17 at 13:33

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.

  • 1
    I love your two exercises. It's a very clever illustration of the gains! – Ben I. Jun 15 '17 at 1:25
  • Re: blind people, I met an Amateur Radio operator who had been blind since birth. He had passed a Morse code reception test at 90 wpm. He could listen to 4 Morse code conversations, reply, and carry on a verbal conversation at the same time. – user737 Jun 17 '17 at 2:03

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.

  • Given the audience, it shouldn't be necessary to ask for explanations of down-votes. Have I upset someone already? – Sean Houlihane May 24 '17 at 17:05
  • with modern editors, keeping the code tidy, to the minimum standards of the language's preferred style book, is usually two keystrokes. – pojo-guy Jul 8 '17 at 4:24

Just teach them Python. That'll work as the whole system relies on indentation and a lack of it will cause errors.

if a > b:
print("Hello, World")

This will give the aptly named "indentation error." It will create a habit in them to always indent everything. I certainly have it. Just typing the example killed me.

  • 2
    When I used to teach a preAP course we started with Python for exactly this reason. By the time we got to Java everybody was indenting. – Ryan Nutt May 28 '17 at 18:32
  • I was about to say the same. Teach Python (or other such indented language) for a while. – Sowmya Jun 7 '17 at 4:27
  • 3
    This is not teaching "indentation is good". All it's teaching is "indentation is annoying and required; it has no benefit to me, and I do it because I'm forced to". – user31 Jun 7 '17 at 16:11

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.

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.

  • I disagree with the first part. Understanding that it makes code understandable to other humans is, in my opinion, essential. – ItamarG3 Jun 7 '17 at 14:30
  • 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 Jun 8 '17 at 0:07

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.

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

  • 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

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.

  • 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 Jul 13 '17 at 18:57

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.

  • 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 Apr 2 at 2:54

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.