Writing maintainable code
It is important to write programSequences of instructions for a computer. 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 debugThe process of finding and correcting programming errors. 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 maintainable codeProgramming code that is easy to understand and amend. style. This includes using:
- comments
- descriptive names for variableA memory location within a computer program where values are stored., constantA value in computer programming that does not change when the program is running. and subprogramA small program that is written within a main program.
- 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 PythonA high-level programming language., for example, a comment begins with a hash symbol, and is printed in red in some IDEIntegrated development environment - a piece of software used to write computer programs., 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 dataUnits of information. In computing there can be different data types, including integers, characters and Boolean. Data is often acted on by instructions. 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 鈥楶I鈥.
Subprograms usually perform a specific task. Giving a descriptive name like 鈥榤ultiply鈥 for a function that multiplies two numbers together is sensible.
Indentation
Code within selection or iterationThe repetition of a block of statements within a computer program. 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.