Chapter 6
Variables

Any non-trivial program will operate on some data. To keep track of this data within our program we use variables. Each variable is identified in our program by a variable name. In this section we will take our first look at variables.

In Chapter 5 we wrote a simple program to print out a standard greeting ‘Hello World!’ to the screen. The message was put into a print statement using quotation marks to delimit the message, this is called a string literal.

String literals in a program are a ’code smell’ (something that is not necessarily wrong but may be evidence that something is in fact wrong). Consider our hello world program, the message is specified in the code, if I want to change the message I need to find the string literal and change the code. This is not a problem in this program (after all, it has only one line) but think about a larger program with many different messages spread through the code. Say I want to change my interface from English to French. I would need to search through all the program code and translate each literal string. Worse, I now have a French interface but the English messages are all gone. If I want German instead of French? Again, every message literal string must be found and translated. This is obviously not a good solution.

The first step in cleaning up our program is to gather the messages in one location. Having all messages in one place means we do not need to search the code for them. In the following sections we will rework our code to use a variable for the message. Importantly we are not changing the behaviour of the program, we expect all of the tests to continue to pass as we modify the code. This process of modifying code to improve it without changing what it does is called ‘refactoring’ and is one of the principal reasons for having good tests in place. Having good tests ensures that whenever we refactor the code to improve its readability, improve performance, simplify it, or make it easier to manage, we can do so confident that the passing tests ensure we are not changing what the code is designed to do.