±«Óătv

Writing maintainable code

It is important to write code that is easy to read and maintain so that extra features can be added later on. Additionally, another programmer may wish to modify the program in order to improve it or an error.

In both situations, the understanding of the program, how it works and the purpose of the code will be made easier if the program is written in a style. This includes using:

  • comments
  • descriptive names for , and
  • indentation

Comments

Comments are lines in programs that provide information about what the different parts of the program do. They serve no other purpose and are not executed when the program is run - the program simply ignores them and moves on to the next line of code.

Different languages express comments in different ways. In , for example, a comment begins with a hash symbol, and is printed in red in some , eg:

#ensures the input is restricted to a y or an n

Descriptive names

Many programmers choose meaningless variable names such as x or y. While a program might run with such names, it is difficult to understand the purpose of the variable. Programmers should choose a variable name that reflects the purpose of the variable and the the variables intended to hold, eg:

h - poor choice. What does it mean?

height - better choice as it describes the value the variable will hold.

The preferred use of descriptive names also applies to constants and subprograms. For example, a constant is often used to hold the value of Pi since this does not change. This can be called ‘PI’.

Subprograms usually perform a specific task. Giving a descriptive name like ‘multiply’ for a function that multiplies two numbers together is sensible.

Indentation

Code within selection or construct should be indented. This allows programmers to easily see which code falls within the selection or iteration, and where it ends.

FOR count FROM 1 TO 10 DO

SEND count TO DISPLAY

END FOR

The indentation of the SEND keyword inside the FOR loop (iteration) shows what parts of the code will be run within the FOR loop.