Note AcademyNote Academy

Computer Science (AS & A Level) 9618 · Chapter 20

Further Programming

Low-level, imperative, object-oriented and declarative programming paradigms (including classes, inheritance, polymorphism, and facts and rules), plus file processing and exception handling.

Written for the 2027–2029 syllabus · 12 min read

A programming paradigm is a way of thinking about and structuring programs: a style that decides how you break down a problem and what a program looks like. Different paradigms suit different jobs. Paper 3 tests your understanding of the characteristics of each; Paper 4 (practical) asks you to write object-oriented code and to process files and handle exceptions in Python, Java or Visual Basic.

20.1 Programming paradigms

Low-level programming

Low-level programming works close to the hardware: machine code (binary) and assembly language (chapter 4).

  • Instructions correspond to individual processor operations; the programmer controls the registers and memory addresses directly and chooses the addressing mode.
  • Programs are fast and small, and give exact control of the hardware.
  • But they are hard to write, read and debug, take much longer to develop, and are machine dependent (not portable).

Used for device drivers, embedded systems, parts of an OS and where speed or memory is critical.

Imperative (procedural) programming

Imperative programming describes how to solve a problem as a sequence of statements that change the program's state (the values of variables) step by step, using sequence, selection and iteration. Procedural programming is the imperative style in which the program is organised into procedures and functions that are called when needed. The program is a series of commands, usually with variables and loops, in the order the programmer wrote them (chapters 9 to 11).

Languages: Pascal, C, and the procedural parts of Python, Java and VB. It is easy to understand and efficient, and good for many tasks, but large programs can be hard to manage when many procedures share and change the same data.

Object-oriented programming (OOP)

Object-oriented programming organises a program around objects that combine data and the code that works on that data.

Key terms:

  • A class is a blueprint (template) that defines the attributes (data) and methods (actions) of a kind of object.
  • An object is an instance of a class: a particular item made from the blueprint, with its own values for the attributes.
  • An attribute (property) is a data item belonging to an object; a method is a subroutine belonging to the class, either a procedure or a function.
  • A constructor is a special method that is called when an object is created and sets up its initial values.
  • Instantiation is the creation of an object from a class.

Example in pseudocode:

CLASS Character
    PRIVATE Name : STRING
    PRIVATE Intelligence : REAL

    PUBLIC PROCEDURE NEW(GivenName : STRING, GivenIntelligence : REAL)
        Name ← GivenName
        Intelligence ← GivenIntelligence
    ENDPROCEDURE

    PUBLIC FUNCTION GetName() RETURNS STRING
        RETURN Name
    ENDFUNCTION

    PUBLIC PROCEDURE Learn()
        Intelligence ← Intelligence * 1.1
    ENDPROCEDURE
ENDCLASS

FirstCharacter ← NEW Character("Royal", 70)    // creates an object
FirstCharacter.Learn()
OUTPUT FirstCharacter.GetName()

The same class in Python:

python
class Character:
    def __init__(self, given_name, given_intelligence):
        self.__name = given_name                 # private by convention
        self.__intelligence = given_intelligence

    def get_name(self):
        return self.__name

    def learn(self):
        self.__intelligence = self.__intelligence * 1.1

first_character = Character("Royal", 70)
first_character.learn()
print(first_character.get_name())

A class diagram: the superclass Character with private attributes Name and Intelligence and public methods, the subclass MagicCharacter that inherits from it, adds the attribute Element and overrides Learn, and two objects created from them, FirstCharacter and FirstMagic, with their values

A class diagram: the superclass Character with private attributes Name and Intelligence and public methods, the subclass MagicCharacter that inherits from it, adds the attribute Element and overrides Learn, and two objects created from them, FirstCharacter and FirstMagic, with their values

The main concepts of OOP:

  • Encapsulation: the data (attributes) and the methods that use it are kept together in the class, and the attributes are private, so they can only be changed through public methods (getters that return a value and setters that change it, which can check that the new value is valid). It protects the data from being changed by mistake and hides the details of how the class works, so the inside can change without affecting the rest of the program.
  • Inheritance: a new class (subclass, child or derived class) takes on the attributes and methods of an existing class (the superclass, parent or base class) and can add its own or change them. It reuses code, so there is less to write and test, and models "is a" relationships (a Dog is an Animal).
  • Polymorphism: the same method name can behave differently for different classes. Overriding: a subclass redefines a method it inherited so it behaves in its own way (every Animal has MakeSound(), but a Dog barks and a Cat meows). Overloading: several methods with the same name but different parameters in one class.
  • Containment (aggregation): a class contains objects of other classes as attributes (a Car has an Engine): a "has a" relationship.
CLASS MagicCharacter INHERITS Character
    PRIVATE Element : STRING

    PUBLIC PROCEDURE NEW(GivenElement : STRING, GivenName : STRING, GivenIntelligence : REAL)
        SUPER.NEW(GivenName, GivenIntelligence)     // call the parent's constructor
        Element ← GivenElement
    ENDPROCEDURE

    PUBLIC PROCEDURE Learn()                        // overrides the parent's method
        IF Element = "fire" THEN
            // increase intelligence by 20%
        ENDIF
    ENDPROCEDURE
ENDCLASS

Benefits of OOP: code is reusable (inheritance), easier to maintain and extend (changes are limited to a class), models real-world things, and suits large programs and team work because classes can be developed and tested separately. Drawbacks: more planning is needed, it can be slower and use more memory, and it takes longer to learn.

Declarative programming

In declarative programming you state what the result should be (the facts and rules) and not how to get it. The language's own inference engine works out the answer. Examples: SQL (you state what data you want, not how to find it; chapter 8) and logic programming in a language such as Prolog.

A Prolog-style program has:

  • Facts: things that are true, written as predicates ending with a full stop.
  • Rules: what can be inferred from other facts, written with :- meaning "if", where a comma means AND.
  • Queries: questions the system answers by searching the facts and rules. A name that begins with a capital letter is a variable.
parent(john, mary).
parent(john, tom).
parent(mary, anna).
female(mary).
female(anna).

mother(X, Y) :- parent(X, Y), female(X).
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).

?- grandparent(john, anna).      % true
?- parent(john, X).              % X = mary ; X = tom
?- mother(mary, anna).           % true

To answer grandparent(john, anna), the system looks for a Y where parent(john, Y) and parent(Y, anna) are both true: Y = mary works. The system answers queries by matching and backtracking (trying other possibilities when one fails).

ParadigmFocusExample
Low-levelControl of hardware, registers and memoryAssembly language
Imperative / proceduralA sequence of statements (and procedures) changing the statePython (procedural style), C
Object-orientedObjects combining data and methodsJava, Python classes
DeclarativeWhat is wanted: facts and rulesSQL, Prolog

20.2 File processing and exception handling

File processing

Programs use files to keep data after they stop, to read in a lot of data, and to share it. For Paper 4 you need to be able to write code to read, write and append to a text file in your chosen language, and to process what it holds. Steps: open the file in a mode (read, write or append), read or write the data, close the file. Python:

python
# write (creates or overwrites)
with open("scores.txt", "w") as file:
    file.write("Amina,72\n")
    file.write("Omar,65\n")

# append (adds to the end)
with open("scores.txt", "a") as file:
    file.write("Sana,88\n")

# read line by line and process each record
total = 0
count = 0
with open("scores.txt", "r") as file:
    for line in file:
        name, mark = line.strip().split(",")    # split into fields
        total = total + int(mark)
        count = count + 1
print("Average:", total / count)

with closes the file automatically. A comma-separated line holds the fields of one record: strip() removes the newline and split(",") makes a list of the fields, and the text values must be converted (int(mark)) before arithmetic. The equivalent in Java uses a BufferedReader or Scanner, and in Visual Basic a StreamReader and StreamWriter.

Records and random files

A file can hold records as well as lines of text. A serial file has the records one after another in the order they were added, and a sequential file keeps them in key order (so a new record means writing a new file or inserting it in place). A random file stores each record at an address worked out from its key (chapter 13), so any record can be read or written directly. In pseudocode a random file is opened FOR RANDOM, SEEK moves to a record's address, and PUTRECORD and GETRECORD write and read one record:

TYPE TStudent
    DECLARE StudentID : INTEGER
    DECLARE Name : STRING
ENDTYPE
DECLARE Pupil : TStudent

OPENFILE "Students.dat" FOR RANDOM
Pupil.StudentID ← 1012
Pupil.Name ← "Amina Khan"
Address ← Pupil.StudentID MOD 100        // hash the key to find the address
SEEK "Students.dat", Address
PUTRECORD "Students.dat", Pupil          // write the record there
SEEK "Students.dat", Address
GETRECORD "Students.dat", Pupil          // read it back
CLOSEFILE "Students.dat"

In Python, Java or Visual Basic, a record is written with the language's own file routines, for example a line of comma-separated fields in a text file, or a binary file when records need to be found by address.

Exceptions and exception handling

An exception is an error that happens while the program is running (run-time) and stops it normally: dividing by zero, a file that cannot be found, an invalid conversion (the text "abc" to an integer), an index outside an array, or running out of memory.

Exception handling is writing code to detect an exception and respond to it so the program can carry on or end cleanly instead of crashing. It makes the program more robust and user friendly: the user gets a helpful message, the program can ask again, and resources are released (files closed) properly. It is especially important for file handling and user input, where errors are outside the programmer's control.

The structure is try ... catch/except: the code that may fail goes in the try block; if an exception occurs, control jumps to the matching except (catch) block; an optional finally block runs whether or not there was an error.

python
try:
    with open("scores.txt", "r") as file:
        for line in file:
            print(line.strip())
except FileNotFoundError:
    print("The file scores.txt could not be found.")
python
valid = False
while not valid:
    try:
        age = int(input("Enter your age: "))
        valid = True
    except ValueError:
        print("Please enter a whole number.")

Cambridge's pseudocode guide has no fixed statements for exception handling, so in an exam answer use the language you have studied or describe the idea in words. As an illustration only, it could be written:

TRY
    OPENFILE "Scores.txt" FOR READ
    // process the file
EXCEPT
    OUTPUT "The file could not be found"
ENDTRY

Java uses try { ... } catch (IOException e) { ... } and Visual Basic Try ... Catch ex As Exception ... End Try.

Test yourself34 flashcards on this chapter.Flashcards →

Practise this chapter

Every past-paper question on these topics, with the mark scheme.