How to Learn to Program: Writing Code Templates

Programming expertise requires knowing and using hundreds of templates

Photo by Patrick Amoy on Unsplash

This article is the fourth in a series of articles on a sequenced instructional approach to teaching computer programming. The steps in the sequence are: 1) Learning how to read code and understand what it does; 2) Learning how to write code from clear instructions; 3) Learning how to read program templates that solve common computer programming problems; and 4) Learning how to write program templates to solve programming problems.

You can learn more about this approach by reading A theory of instruction for introductory programming skills by Benjamin Xie and his fellow researchers at the University of Washington.

What is a Program Template?

A program template is a pattern of common code usage that can be applied to a programming problem. For example, the technique for swapping two variable values, used in sorting algorithms, is a program template because it can be applied any time you need to swap variable values.

Processing all the elements of an array (or vector or list) is another example of a program template. There are many, many program templates the learning programmer needs to learn in order to become an expert programmer. Programming expertise requires knowing and using hundreds of templates.

Expert Programmers Think in Program Template Chunks

As I explained in my article on reading program templates, program templates represent “chunks” of knowledge programmers need to be able to pull up almost instantaneously when solving programming problems. You can think of program templates like board positions in a chess match that chess grandmasters learn in order to use them to win a match.

Chess grand masters don’t get that way by just playing lots and lots of chess matches, though they do need to play lots of matches to become an expert. What they do is they spend hours studying the board positions of past famous chess matches to learn what positions are favorable for winning a match and how to get into those positions in order to defeat their opponent.

For beginning and intermediate computer programmers, program templates are like these chess board position chunks. By learning which templates should be used for solving most common programming problems, the programmer can access a template from memory with little work and instead use their brain power for more creative purposes.

Writing Program Templates Follows Understanding Program Templates

The step before using program templates to solve problems is learning about the different program templates that are available. Program templates are learned based on the program construct you are currently studying.

If you are just starting out and learning about variable assignment, it is appropriate to learn the program template for variable swapping. If you are working on branching statements, it is appropriate to learn the min/max template for determining the largest or smallest value from a data set. If you are learning about loops, the read one element then process it template is ripe for exploration.

I discussed how to learn to read program templates in a recent article and if you are just coming to this article without having read that one, go back and read it and I’ll be here when you get back.

How to Learn to Write Program Templates

As I’ve said, you can’t start writing program templates until you’ve practiced reading them and understanding their syntax and their logic. Then you can begin applying program templates to problems.

Let’s look at some problems and the templates that solve them. Many of these examples are taken from the paper by Benjamin Xie I referenced at the beginning of this article.

We’ll start with a variable swap problem: Cynthia has two mice that she uses with her laptop, but one of them is better contoured to her hand and she needs to use that one for the long project she is about to do. Unfortunately, the battery in that mouse is about drained and her other mouse has a stronger battery. Cynthia asks us to write a JavaScript program for her to exchange the batteries in her two mice so she can work longer with the better mouse.

Here’s the program:

let mouse1_battery = 1; // number indicates the battery charge
let mouse2_battery = 10;
let temp_mouse = mouse1_battery;
mouse1_battery = mouse2_battery;
mouse2_battery = temp;

The crucial concept to understand is that two exchange the two batteries, a temporary mouse must be used to hold a battery while one mouse is without a battery.

I have also demonstrated this concept physically by asking two students to come to the front of the class and put one hand behind their back. Then I give each of them a different colored marker and ask them to exchange markers without using the other hand and without dropping a marker. Of course, they can’t do it and must ask a third student (the temporary variable) to come to the front to help them. Programming instructors should spend more time creating physical demonstrations of the abstract concepts of computer programming.

Find the Minimum/Maximum

Here is an example of a branching template (JavaScript using the Spidermonkey shell): Find the minimum and maximum grades in a set of three grades entered by the user.

Here is the program:

putstr("Enter the first grade: ");
let grade1 = parseInt(readline());
putstr("Enter the second grade: ");
let grade2 = parseInt(readline());
putstr("Enter the third grade: ");
let grade3 = parseInt(readline());
let max = 0;
if (grade1 > grade2 && grade1 > grade3) {
  max = grade1;

}
else if (grade2 > grade1 && grade2 > grade3) {
  max = grade2;
}
else {
  max = grade3;
}
print("The max grade is",max);

For this template, the key concept is that each element must be tested against the other two elements and the comparisons must be made for all possibilities. In this case, there were three variables to compare but the template works for any number of compared elements.

Input – Process – Output

The last template we’ll look at is “input-process-output”. I usually start out a class of new programmers by telling them that this template is really the essence of every computer program, and it is certainly appropriate for the first few lessons in programming where students are learning how to assign values to variable and manipulate the variables using arithmetic or maybe some simple string processing (concatenation, for example).

The type of problem I use to test my students ability to recognize this template is like this one in C++: Prompt the user to enter three test scores with one prompt. Define a constant that represents the number of test scores. Sum the variables to get the total and then divide the total by the number of test scores to get the average. Display the average to the user using appropriate output (meaning more than just the bare number).

To demonstrate their knowledge of the template, I have them comment each part of the template.

Here is one student solution to the problem:

// input
int grade1, grade2, grade3;
const int NUM_GRADES = 3;
cout << "Enter three test scores, separated by a space: ";
cin >> grade1 >> grade2 >> grade3;
// process
int total = grade1 + grade2 + grade3;
double average = total / NUM_GRADES;
// output
cout << "The average of the test scores is: "
     << average << endl;

This solution does everything right except accurately compute the average. The reason is C++ does integer division so since the variable total is an integer and the constant NUM_GRADES is an integer, the result of the division is also an integer.

I have already taught them about integer division but it usually takes two or three programs before the concept sticks in their heads, so I remind them they must convert one of the operands in the average calculation to a floating-point type.

Program Templates are Pervasive in Computer Programming

There are many more program templates, of course, then I’ve demonstrated here. One of the best, and only, template-based introductory computer programming textbooks I’m aware of, Designing Pascal Solutions by Michael Clancy and Marcia Linn, identifies twenty templates that should be learned. There are many more for more advanced computer programming concepts, such as design patterns for object-oriented programming and the many algorithms used for searching and sorting data and for use with advanced data structures such as graphs and trees.

Become an Expert by Chunking Program Templates

Just as chess players improve their play by “chunking” the board positions of famous chess matches of the past, student programmers should be studying program templates so that they become chunks in the programmer’s mind. How do you do this? First, you must learn what the many different program templates are and where and when they are appropriate to use. Then, you need to practice using them on programming problems until their use becomes second nature.

And finally, you must keep extending your command of program templates by moving on to newer and more challenging programming problems. Try solving problems in a domain you’re not familiar with. If you are comfortable using imperative and object-oriented languages, spend a few months learning a functional language. If you are getting too complacent using relational databases, try using a NoSQL database on your next project. In all of these new domains, try to use the program templates you’ve learned to solve problems, and if the templates don’t apply in that domain, you’ll be learning new templates you can add to your toolbox.

And remember that expertise is a journey, not a destination.