Code Tracing
Moving beyond tools for reducing cognitive load on our students, let’s turn our attention to specific activities we can employ in our teaching. Perhaps one of the most important, and commonly overlooked, is reading code. Think for a moment about how writing a program is like writing a story or essay. You wouldn’t ask a student to write a story until after they have read many examples of stories, would you? Likewise, when we introduce essay writing, we first have students read many good examples of essays. The same should be true of programming - students learn to write good programs in part from reading good programs.
But how do we read a program? There is a specific strategy we employ known as code tracing, and it refers to evaluating what happens in a program on a line-by-line basis. You start at the entry point of the program - the first line that is executed (often the first line for many programming languages, though for C/C++, Java, and C# it will be the first line in the main
method).
Then, for each line, you determine what that line is doing. If it carries out a calculation, you carry out the calculation. If it declares a variable, you draw a box on a piece of scratch paper to represent the variable. If it assigns a value to that variable, you write the value in the box. If you reach a branching point (i.e. an if
statement), you determine which branch to follow based on its test condition. And if you enter a loop, you repeat the lines of code in the loop until its test condition is no longer true.
Below are some example videos walking through code tracing with Scratch and Java:
The Developmental Epistemology of Programming we discussed in the prior chapter claims that when students are able to trace code with greater than 50% accuracy, they have moved into the preoperational stage, which marks initial readiness to start programming. Remember, that stage is specific to each code construct, so as you introduce new operations (like loops) you will need to repeat code tracing with examples of the new syntax.
It is also important to note that as students develop cognitive structures to reason about programs, they will need to perform line-by-line code traces less and less. Eventually, they will be able to recognize the purpose of multiple lines of code at a glance, i.e. when presented with this code:
bool sorted = true;
for(int i = 0; i < numbers.length -1; i++)
{
if(numbers[i] > numbers[i+1])
{
sorted = false;
break;
}
}
They will recognize that it is testing the array numbers
to determine if it is sorted in ascending order. This ability to recognize the purpose from a pattern of code corresponds with the Formal Operational stage.