32
$\begingroup$

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?

$\endgroup$
7
  • 2
    $\begingroup$ 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. $\endgroup$
    – Aurora0001
    May 24, 2017 at 13:24
  • 22
    $\begingroup$ 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. $\endgroup$
    – Nat
    May 24, 2017 at 13:52
  • $\begingroup$ @Nat I'm going to have to steal your April 1st idea. That's great. $\endgroup$
    – Ryan Nutt
    May 25, 2017 at 1:30
  • 9
    $\begingroup$ 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. $\endgroup$ May 26, 2017 at 12:58
  • 3
    $\begingroup$ Why is it a hassle? Don't they use editors that indent automatically? $\endgroup$
    – Barmar
    May 20, 2018 at 7:41

13 Answers 13

41
$\begingroup$

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.

$\endgroup$
7
  • 2
    $\begingroup$ number four is in a way inter-student "community moderation" of code. $\endgroup$
    – ItamarG3
    May 27, 2017 at 12:41
  • $\begingroup$ Introduce them to some examples from code golf $\endgroup$
    – pojo-guy
    Jul 8, 2017 at 4:18
  • $\begingroup$ 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. $\endgroup$ Sep 15, 2020 at 16:15
  • $\begingroup$ @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) $\endgroup$
    – Ben I.
    Sep 16, 2020 at 11:58
  • $\begingroup$ (cont) names in loop headers if the loops aren't crystal clear on their own. $\endgroup$
    – Ben I.
    Sep 16, 2020 at 11:58
17
$\begingroup$

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.

$\endgroup$
2
  • 3
    $\begingroup$ This applies not only to indentation, but also to issues such as naming and comments. $\endgroup$ Jun 7, 2017 at 17:42
  • 1
    $\begingroup$ I really like the idea of having them trace messy code. Might have to try that next year. $\endgroup$
    – Ryan Nutt
    Mar 29, 2018 at 17:35
9
$\begingroup$

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.

$\endgroup$
3
  • 1
    $\begingroup$ I love your two exercises. It's a very clever illustration of the gains! $\endgroup$
    – Ben I.
    Jun 15, 2017 at 1:25
  • 1
    $\begingroup$ 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. $\endgroup$
    – user737
    Jun 17, 2017 at 2:03
  • $\begingroup$ 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. $\endgroup$
    – ObscureOwl
    Jan 27, 2021 at 13:39
9
$\begingroup$

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.

$\endgroup$
1
  • 7
    $\begingroup$ Another example you could add would be asking the students to debug unindented code v. indented code. $\endgroup$
    – thesecretmaster
    May 24, 2017 at 13:33
6
$\begingroup$

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.

$\endgroup$
3
  • 2
    $\begingroup$ 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. $\endgroup$
    – Ryan Nutt
    May 28, 2017 at 18:32
  • $\begingroup$ I was about to say the same. Teach Python (or other such indented language) for a while. $\endgroup$
    – Sowmya
    Jun 7, 2017 at 4:27
  • 4
    $\begingroup$ 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". $\endgroup$
    – user31
    Jun 7, 2017 at 16:11
6
$\begingroup$

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.

$\endgroup$
5
$\begingroup$

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.

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

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.

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

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.

$\endgroup$
3
  • 2
    $\begingroup$ 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. $\endgroup$
    – ivanivan
    Apr 2, 2018 at 2:54
  • $\begingroup$ Agreed that in the context where I teach, massively non-indented code is usually a sign of code copied from another source. $\endgroup$ Jan 20, 2020 at 19:23
  • $\begingroup$ 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. $\endgroup$
    – ObscureOwl
    Jan 27, 2021 at 13:50
3
$\begingroup$

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

$\endgroup$
3
$\begingroup$
  • 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
$\endgroup$
2
$\begingroup$

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.

$\endgroup$
1
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ 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). $\endgroup$ Jul 13, 2017 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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