Skip to content

9618 · Unit 25 · Papers 3–4: Theory and practical programming

Programming paradigms and object-oriented design.

9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Programming paradigms

§20.1 · Programming paradigms and object-oriented design

Ask four programmers to find Tavren’s available lanterns and you may get four different programs: a loop, a set of objects, processor instructions, or facts and a question. Each is a programming paradigm, a style of organising and expressing a solution. The loops you already write are procedural.

Four ways to express the same work

Each style leaves its own marks in the code. Be able to name each paradigm and recognise its code.

ProceduralFOR Index ← 1 TO 6 IF Ready[Index] THEN Count ← Count + 1Object-orienteditem.GetStatus()item.SetStatus("on-loan")Low-levelLDD STATUSCMP #1JPE FOUNDDeclarativeavailable(31).can_supply(L, courtyard).

In words, what gives each style away when it does Tavren’s lantern work:

ParadigmHow it expresses Tavren’s work
Imperative / proceduralAn ordered sequence changes variables; procedures and functions group the steps. A loop checks each lantern and appends matches.
Object-orientedClasses combine state and operations. Each lantern object stores its own status and exposes methods that read or change it.
Low-levelInstructions use a processor’s operations, registers and addresses. A selection loop becomes loads, comparisons and branches.
DeclarativeFacts and rules describe relationships. A goal asks which lanterns satisfy compatibility and availability conditions.

A language can support more than one approach

  • Python can express the procedural loop and the object design.
  • Using a function alone does not make a program object-oriented: the class design must connect state with behaviour.

The design, step by step

Tavren’s lanterns are built as objects in three steps:

1
Describe one lantern’s data and valid operations.
2
Create distinct objects from that shared class definition.
3
Extend a specialised lantern and group lantern references in a hire.
Your turn

1 Which paradigm groups data and methods together in classes?

2 Which paradigm states facts and rules, then asks a goal?

3 Which paradigm works with registers, addresses and branches?

  1. 1
    object-oriented
  2. 2
    declarative
  3. 3
    low-level
Tick what you can do now
Practise with w21/31 Q2 (older paper: paradigm comparison)
1 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Classes and instances

§20.1 · Programming paradigms and object-oriented design

Every one of Tavren’s lanterns has its own ID and status, yet each is read and changed in exactly the same ways. So the design is written once and used for them all. That design is a class; each lantern made from it while the program runs is an object, or instance.

Python · create two instances, change only a
a = Lantern(31, 6)
b = Lantern(14, 9)
a.SetStatus("on-loan")
print(a.GetStatus())
print(b.GetStatus())

Follow each name along its arrow. a and other end at the same lantern; b ends at a separate one, so a change made through a never reaches b.

Lantern · shared class definitiondefines attributes and methodsinstantiateReferencesLantern objectID 31 · 6 WStatus = on-loanaotherAfter alias assignment: other = aSeparate Lantern objectID 14 · 9 WStatus = availableb

One class, separate objects

  1. 1
    The output is on-loan, then available.
  2. 2
    Both objects offer GetStatus() and SetStatus(). The object before the dot decides whose state the method uses.
  3. 3
    Changing a leaves b unchanged.
other = a gives another reference to a; it does not instantiate a second lantern. other.SetStatus("repair") would also change the status read through a.
Your turn

1 After the code above, b.SetStatus("repair") runs. What does a.GetStatus() return?

2 Then other = a and other.SetStatus("repair") run. What does a.GetStatus() return now?

3 How many Lantern objects exist after a = Lantern(31, 6), b = Lantern(14, 9) and other = a?

  1. 1
    on-loan: b’s change does not touch a
  2. 2
    repair: other and a refer to the same object
  3. 3
    2
Tick what you can do now
Practise with s26/32 Q11(b); s25/32 Q12(b)(i) (older paper: instance)
2 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Encapsulation, getters and setters

§20.1 · Programming paradigms and object-oriented design

If any code could write to a lantern’s status, one typing slip could store nonsense. Encapsulation keeps an object’s data with the methods that use it and controls access to that data. Tavren changes a status only through a method, so an invalid status cannot get in that way.

Python · status interface
class Lantern:
# ID, Watts: INTEGER; Status: STRING
def __init__(self, lantern_id, watts):
self.__ID = lantern_id
self.__Watts = watts
self.__Status = "available"
def GetStatus(self):
return self.__Status
def SetStatus(self, status):
if status not in ("available", "on-loan", "repair"):
return False
self.__Status = status
return True
  • A setter changes an attribute. SetStatus accepts one new status and returns whether the update succeeded.
  • A getter returns the stored value without changing it.

How callers reach the private data

Outside code never touches the data directly. Be able to say what happens to each call.

SetStatus("repair")returns True: storedSetStatus("missing")returns False: rejecteda : Lanternpublic+ SetStatus(status)+ GetStatus()private− ID = 31− Watts = 6− Status = repair

Now make both calls and see what the caller gets back each time.

Python · caller tests valid and invalid updates
a = Lantern(31, 6)
print(a.SetStatus("repair"))
print(a.SetStatus("missing"))
print(a.GetStatus())

Output: True, False, repair. The invalid update returns False and leaves the stored status unchanged.

Attributes, methods and properties

  • An attribute stores data; a method is an operation.
  • A property can expose an attribute through getter/setter access. These listings use explicit methods, not Python’s property syntax.
The double underscore in __Status uses Python name mangling to discourage accidental outside access. It is not a security barrier. A setter is needed only for data the requirements allow to change.
Your turn

1 c = Lantern(8, 6) then print(c.SetStatus("lost")). What is printed?

2 What does c.GetStatus() return after that?

3 Why does Lantern have no SetID method?

  1. 1
    False
  2. 2
    available: the rejected value was never stored
  3. 3
    a lantern’s ID must never change, so no method is offered to change it
Tick what you can do now
Practise with s26/32 Q11(b); s26/42 Q2(a)(ii)
3 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Constructors and methods

§20.1 · Programming paradigms and object-oriented design

A new lantern should never exist without its ID and wattage. A constructor runs when an object is created, so it sets them at once. Its parameters give the starting values; the object’s attributes keep those values after the constructor finishes.

Python
class Lantern:
# ID, Watts: INTEGER; Status: STRING
def __init__(self, lantern_id, watts):
self.__ID = lantern_id
self.__Watts = watts
self.__Status = "available"

What self refers to

Follow each argument along its arrow: into a parameter first, then into the new object, which a ends up referring to.

a = Lantern(31, 6)parametersnew Lantern objectlantern_id = 31watts = 6__ID = 31__Watts = 6__Status = 'available'set by the constructorareference to the new object
  1. 1
    For a = Lantern(31, 6), Python passes the new object as self.
  2. 2
    31 goes into lantern_id and 6 into watts; the constructor stores them in self.__ID and self.__Watts.
  3. 3
    A parameter is local to the call; the attribute is what the object keeps.

Once the object exists, each later call supplies only what that method needs:

Call and caller-supplied parametersResult
Lantern(31, 6) · ID and wattageA new reference assigned to a; status starts available.
a.GetWatts() · noneThe integer 6 is returned.
a.SetStatus("on-loan") · new statusState changes; Boolean True is returned.

The same class in pseudocode

Pseudocode spells out what Python leaves unsaid: each attribute’s type and access level.

NotationRole
CLASS Lantern … ENDCLASSEncloses a class definition.
PRIVATE ID : INTEGERDeclares a private attribute and its type.
PUBLIC PROCEDURE NEW(Number : INTEGER, Power : INTEGER)Begins the constructor; assign parameters to attributes before ENDPROCEDURE.
a ← NEW Lantern(31, 6)Creates a new instance and assigns its reference to a.

Access levels are PRIVATE or PUBLIC when relevant. Methods use the object identifier and a dot, as in a.GetWatts().

Your turn

1 b = Lantern(22, 12). What does b.GetWatts() return?

2 What status does every new Lantern start with?

3 Write the pseudocode that creates lantern 19 with 9 W and assigns it to c.

  1. 1
    12
  2. 2
    available
  3. 3
    c ← NEW Lantern(19, 9)
Tick what you can do now
Practise with s26/32 Q11(a); s26/43 Q2(a)(i)
4 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Designing classes from requirements

§20.1 · Programming paradigms and object-oriented design

Before anyone types class Lantern, someone decides what a lantern must remember and what staff may do to it. Tavren’s rules: each ID and wattage is fixed, staff read both, and the status may change to available, on-loan or repair. Each rule becomes a member of the class.

A class diagram has three compartments: name, attributes, methods. The black numbers tie each member to the requirement it serves.

Lantern− ID : INTEGER1− Watts : INTEGER2− Status : STRING3+ NEW(number : INTEGER, watts : INTEGER)+ GetID() : INTEGER1+ GetWatts() : INTEGER2+ GetStatus() : STRING3+ SetStatus(status : STRING) : BOOLEAN3+ SupplyDetails() : STRING4nameattributesmethods
Lantern

− ID : INTEGER
− Watts : INTEGER
− Status : STRING

+ NEW(number : INTEGER, watts : INTEGER)
+ GetID() : INTEGER
+ GetWatts() : INTEGER
+ GetStatus() : STRING
+ SetStatus(status : STRING) : BOOLEAN
+ SupplyDetails() : STRING

  • − means private; + means public.
  • Top compartment: the class name. Middle: attributes and types. Bottom: methods, parameters and result types.

Turn each requirement into members

Each numbered requirement matches the members with the same number in the diagram.

RequirementDesign consequence
1 Identify a lantern permanentlyID is an INTEGER initialised by the constructor; GetID returns it. No SetID method is exposed.
2 Keep a fixed wattageWatts is an INTEGER initialised by the constructor; GetWatts returns it.
3 Control changing hire stateStatus is a STRING. GetStatus reads it; SetStatus checks and updates it.
4 Describe the supplySupplyDetails returns a STRING; specialised classes can redefine it.
Keep identifiers and types consistent from requirements to diagram to code. A method that returns an ID needs a return value; printing it alone does not supply the caller with that value.
Your turn

1 Which members of Lantern are private?

2 Why is there no SetWatts method?

3 What type does SetStatus return, and why?

  1. 1
    ID, Watts and Status
  2. 2
    the wattage is fixed, so nothing may change it after the constructor
  3. 3
    BOOLEAN: it tells the caller whether the update was accepted
Tick what you can do now
Practise with s26/32 Q11(a); s25/32 Q12(a) (older paper: class diagram)
5 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Inheritance

§20.1 · Programming paradigms and object-oriented design

Some of Tavren’s lanterns run on batteries, and writing a whole new class for them would copy every method. Inheritance derives a more specialised subclass from a superclass (base or parent class). A BatteryLantern is a Lantern: it reuses lantern operations and adds a battery runtime.

BatteryLantern lists only what it adds; the hollow triangle brings in everything else from Lantern. Object c shows both parts together in one lantern.

Lantern− ID : INTEGER− Watts : INTEGER− Status : STRING+ GetID(), GetWatts()+ GetStatus(), SetStatus()+ SupplyDetails()inheritsBatteryLantern− Runtime : INTEGER+ NEW(number, watts, runtime)+ GetRuntime() : INTEGER+ SupplyDetails()c : BatteryLanternID27Watts12StatusavailableRuntime6top three: inherited partRuntime: added by the subclass
LanternID · Watts · Statusis aBatteryLanterninherits members; adds Runtime
Python
class BatteryLantern(Lantern):
# Runtime: INTEGER, in hours
def __init__(self, lantern_id, watts, runtime):
super().__init__(lantern_id, watts)
self.__Runtime = runtime

def GetRuntime(self):
return self.__Runtime

How the subclass constructor works

  1. 1
    super().__init__(lantern_id, watts) calls the parent constructor. It sets ID, Watts and Status for this same object.
  2. 2
    The next line sets Runtime, the attribute the subclass adds.
  3. 3
    Inherited getters read the parent’s private attributes; the subclass does not access them directly.

Pseudocode names the parent in the class header and calls its constructor through SUPER:

2026 pseudocode notationMeaning
CLASS BatteryLantern INHERITS LanternNames the subclass and its parent.
SUPER.NEW(Number, Power)Calls the parent constructor from the subclass constructor.
Runtime ← HoursInitialises the subclass’s additional attribute.
The hollow triangle points towards the parent. A subclass has inherited members even when the diagram lists only its additional members.
Your turn

1 d = BatteryLantern(19, 9, 4). What do d.GetWatts() and d.GetRuntime() return?

2 What does d.GetStatus() return, and which constructor set it?

3 In a class diagram, which way does the hollow triangle point?

  1. 1
    9 and 4
  2. 2
    available: set by the Lantern constructor, called through super()
  3. 3
    towards the parent (superclass)
Tick what you can do now
Practise with s26/32 Q11(b); s25/31 Q11(b)(ii) (older paper: inheritance)
6 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Polymorphism

§20.1 · Programming paradigms and object-oriented design

A battery lantern and a mains lantern describe their power supply differently, yet a caller should ask both the same way. Polymorphism lets the same method name behave differently in derived classes. The object’s actual class decides which version runs.

Python · subclass overrides SupplyDetails
class BatteryLantern(Lantern):
# Runtime: INTEGER, in hours
def __init__(self, lantern_id, watts, runtime):
super().__init__(lantern_id, watts)
self.__Runtime = runtime

def GetRuntime(self):
return self.__Runtime
def SupplyDetails(self):
return str(self.__Runtime) + " hours on battery"

The parent’s SupplyDetails method returns "external supply". The subclass defines the same method name and returns a description using its own runtime.

Python · one caller for both classes
devices = [Lantern(31, 6), BatteryLantern(27, 12, 6)]
for item in devices:
print(item.GetID(), item.SupplyDetails())

One call, a different version per class

Follow item.SupplyDetails() down each branch, once for each object in the list.

item.SupplyDetails()item is Lantern 31runs Lantern’s method"external supply"item is BatteryLantern 27runs its own override"6 hours on battery"the caller writes one call; the object’s class picks the method
Actual classResult of item.SupplyDetails()
Lanternexternal supply · the parent implementation.
BatteryLantern6 hours on battery · the override reads its stored runtime.
  • Inheriting the method unchanged reuses its behaviour. Overriding it gives the specialised behaviour while the caller keeps the same call.
  • Changing an attribute’s value alone is not this form of polymorphism.
Your turn

1 What does BatteryLantern(19, 9, 4).SupplyDetails() return?

2 What does Lantern(8, 6).SupplyDetails() return?

3 The override is deleted from BatteryLantern. What does BatteryLantern(19, 9, 4).SupplyDetails() return now?

  1. 1
    "4 hours on battery"
  2. 2
    "external supply"
  3. 3
    "external supply": the inherited parent method runs
Tick what you can do now
Practise with s25/32 Q12(b)(ii) (older paper: polymorphism)
7 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Containment and aggregation

§20.1 · Programming paradigms and object-oriented design

A customer’s hire is made up of lanterns, but a hire is not itself a lantern, so inheritance is the wrong tool. Containment / aggregation is a has-a relationship: a hire holds references to lantern objects that already exist.

Read the diagram as “a Hire has Lanterns”: the hollow diamond sits at the Hire end. The Hire class keeps those references in a list.

HireLanternHollow diamond: aggregate endHire: eveningOwn Lanterns list[0][1]Lantern 316 W · on-loanLantern 2212 W · availableaoutside hireList entries and a reach the existing objects.
Python · each hire owns its list
class Hire:
def __init__(self, hire_id):
self.__ID = hire_id
self.__Lanterns = []

def AddLantern(self, lantern):
self.__Lanterns.append(lantern)

def GetLantern(self, index):
return self.__Lanterns[index]

Run the caller and follow hire.GetLantern(0): it reaches the same Lantern 31 that a names.

Python · caller stores and follows references
a = Lantern(31, 6)
b = Lantern(22, 12)
hire = Hire("evening")
hire.AddLantern(a)
hire.AddLantern(b)
hire.GetLantern(0).SetStatus("on-loan")
print(a.GetStatus())

Store a reference, not a copy

  • Each new Hire constructs its own empty list.
  • Lantern objects can exist before the hire and stay in the wider stock system afterwards.
BatteryLantern is a Lantern; Hire has Lantern references.
Your turn

1 A hire holds a then b, with b = Lantern(22, 12). What does hire.GetLantern(1).GetID() return?

2 Then hire.GetLantern(1).SetStatus("repair") runs. What does b.GetStatus() return?

3 Hire and Lantern: is-a or has-a? BatteryLantern and Lantern?

  1. 1
    22
  2. 2
    repair: the list holds a reference to b itself
  3. 3
    Hire has Lanterns (aggregation); BatteryLantern is a Lantern (inheritance)
Tick what you can do now
Practise with s26/32 Q11(b)
8 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Loading objects from files

§20.1 · Programming paradigms and object-oriented design

Objects vanish when the program stops, so each run builds them again from the stock file. Each record read from a file becomes a new object. The loader returns an array of references, so later code can select through getters.

Lanterns.txt holds one ID|Wattage|Status record per line. The job is to turn each line into a Lantern object.

Lanterns.txt · ID|Wattage|Status
31|6|available
14|9|on-loan
27|12|repair
8|6|available
22|12|available
19|9|on-loan

Read the loop body: each pass splits one line and constructs a fresh Lantern from its fields.

Python · loader and successful call
def ReadLanterns(filename):
lanterns = []
try:
with open(filename) as source:
for line in source:
fields = line.strip().split("|")
number, watts, status = fields
item = Lantern(int(number), int(watts))
item.SetStatus(status)
lanterns.append(item)
except OSError:
print("Cannot read lantern file")
return []
return lanterns

stock = ReadLanterns("Lanterns.txt")

One line, one new object

Every line must give a lantern of its own. Be able to say what each array element refers to.

Lanterns.txtstockLantern objects31|6|available[0]31 · 6 W · available14|9|on-loan[1]14 · 9 W · on-loan27|12|repair[2]27 · 12 W · repair8|6|available[3]8 · 6 W · available22|12|available[4]22 · 12 W · available19|9|on-loan[5]19 · 9 W · on-loan

Test a missing file too

Python · missing-file caller
stock = ReadLanterns("Missing.txt")
print("Loaded:", len(stock))
  • Output: Cannot read lantern file, then Loaded: 0.
  • If opening or reading raises OSError, the handler returns an empty array, not a partly loaded one.
  • The with statement closes an opened file on success or failure.
Every row is assumed valid. Create each object inside the loop: constructing one object outside it and repeatedly appending that reference would not create separate lanterns.
Your turn

1 How many Lantern objects does ReadLanterns("Lanterns.txt") create?

2 What does it return when the file is missing?

3 The line item = Lantern(...) is moved above the loop. What goes wrong?

  1. 1
    6, one per line
  2. 2
    an empty array, after printing Cannot read lantern file
  3. 3
    every element refers to the same single object, so there are no separate lanterns
Tick what you can do now
Practise with s26/43 Q2(b)
9 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Selecting objects from arrays

§20.1 · Programming paradigms and object-oriented design

A customer wants an available lantern of at least 9 W. Keep only the objects that meet both criteria, then output their count and details using getters.

Staff enter a required hire status and a minimum wattage. ReadLanterns loads the six lanterns from Lanterns.txt.

Lanterns.txt holds ID/watts/status records: 31/6/available; 14/9/on-loan; 27/12/repair; 8/6/available; 22/12/available; 19/9/on-loan.

SelectLanterns does the filtering. It asks each object for its status and watts through getters and keeps the ones that pass both tests.

Python · return references meeting both criteria
def SelectLanterns(lanterns, wanted_status,
minimum_watts):
selected = []
for item in lanterns:
if (item.GetStatus() == wanted_status
and item.GetWatts() >= minimum_watts):
selected.append(item)
return selected

The main program reads the two criteria, hands the whole stock to SelectLanterns, then reports what comes back.

Python · read two inputs, then count and output matches
print("Enter status")
wanted_status = input().lower()
print("Enter minimum watts")
minimum = int(input())
stock = ReadLanterns("Lanterns.txt")
matches = SelectLanterns(stock, wanted_status,
minimum)
print("Matches:", len(matches))
for item in matches:
print(item.GetID(), item.GetWatts(),
item.GetStatus())
Inputs available, 9 · observed output
Enter status
Enter minimum watts
Matches: 1
22 12 available

Each object tested against both criteria

Inputs available and 9. The status test runs first; the watts test only if it passes.

StatusWattsStatus testWatts testResult
ID 31available6yesnorejected: 6 W is under 9
rejected: 6 W is under 9
ID 14on-loan9no—rejected: status is on-loan
rejected: status is on-loan
ID 27repair12no—rejected: status is repair
rejected: status is repair
ID 8available6yesnorejected: 6 W is under 9
rejected: 6 W is under 9
ID 22available12yesyeskept: both tests pass
kept: both tests pass
ID 19on-loan9no—rejected: status is on-loan
rejected: status is on-loan

What the selection stores

  • Only ID 22 is available and at least 9 W. ID 27 has enough power but is in repair.
  • selected.append(item) stores the existing reference: both arrays refer to the same lantern. No object is created or copied.
  • For inputs repair, 9, only ID 27 matches. For available, 13, the count is 0 and the loop prints no details.
Your turn

1 The inputs are on-loan and 9. Which IDs match, and what count is printed?

2 The inputs are available and 6. Which IDs match?

3 Does matches hold copies of the lanterns?

  1. 1
    14, 19: Matches: 2
  2. 2
    31, 8, 22
  3. 3
    no: it holds references to the same objects as stock
Tick what you can do now
Practise with s26/43 Q2(e)(i); s26/42 Q2(c)(ii)
10 / 11
9618 · Unit 25 · Programming paradigms and object-oriented design
Revisionbyexamplicity

Testing the object model

§20.1 · Programming paradigms and object-oriented design

A class can run yet mix up two lanterns, so test it through its public methods. Each result should show one thing: separate instances, rejected changes, inherited members or overridden behaviour.

Each test aims at one thing that could go wrong. The last column says what a failure would tell you.

TestExpected resultWhat a failure exposes
Create a(31, 6) and b(14, 9); set only a to on-loana is on-loan; b stays availableShared state or the wrong receiver.
Attempt status missing after repairFalse; status stays repairAn update performed before validation.
Create BatteryLantern(27, 12, 6)GetID = 27; GetWatts = 12; Runtime = 6Parent constructor omitted or parameters misplaced.
Call SupplyDetails on both classesexternal supply / 6 hours on batteryMissing override or an incorrect method name.
Store a in a Hire; change through the hireReading a shows the changed statusAn accidental copy rather than a shared reference.

The same tests as assertions: the message prints only if every one holds.

Python
a = Lantern(31, 6)
b = Lantern(14, 9)
assert a.SetStatus("repair")
assert not a.SetStatus("missing")
assert a.GetStatus() == "repair"
assert b.GetStatus() == "available"
c = BatteryLantern(27, 12, 6)
assert c.GetWatts() == 12
assert c.SupplyDetails() == "6 hours on battery"
print("object checks passed")

Which relationship for which requirement

Each requirement calls for one of these; be able to choose.

UseFor
classone lantern’s state and operations
instancesdistinct physical lanterns
inheritancea specialised lantern
polymorphismone shared call with specialised behaviour
aggregationa hire containing existing lanterns
An assertion checks an expected condition and fails if it is false. It is a test aid; the normal caller still uses return values and the required input/output flow.
Your turn

1 Which test in the table would catch a missing override?

2 A hire must hold lanterns that already exist. Which relationship do you use?

3 What happens when an assertion’s condition is false?

  1. 1
    calling SupplyDetails on both classes
  2. 2
    aggregation (containment)
  3. 3
    the program stops with an AssertionError, so the test fails
Tick what you can do now
Practise with s26/42 Q2(c)(ii); s26/43 Q2(d)(ii)
11 / 11