Choose and design an appropriate user-defined data type for a given problem

13.1 User‑Defined Data Types

Learning Objective

Choose and design an appropriate user‑defined data type for a given problem, justify the design against the Cambridge 9618 syllabus, and implement it in pseudo‑code and a chosen programming language.

Why Use User‑Defined Types?

  • Encapsulation: Group related data items into a single logical entity.
  • Abstraction: Hide implementation details; the rest of the program works with the abstract type.
  • Type‑checking: The compiler/interpreter can detect mismatched uses at compile time.
  • Maintainability: Changing the definition (e.g., adding a field) only requires updating the type declaration.
  • Readability: Code that manipulates a meaningful name (e.g., Book) is easier to understand than a collection of unrelated variables.

Types of User‑Defined Data Types

CategoryDefinitionTypical Use in A‑Level
Enumerated type (enum)A set of named constant values.Days of the week, traffic‑light colours, menu options.
Record / StructureA collection of fields of possibly different primitive types.Library book, student record, exam result.
Class / ObjectA record plus associated behaviour (methods) and optional inheritance.When data and operations must be bundled, e.g., a Book class with borrow() and return() methods.

Design Process for a User‑Defined Type

  1. Analyse the problem – Identify real‑world entities to model.
  2. List required attributes – Decide what information each entity must store.
  3. Choose the representation – Enum, record, or class based on data‑only vs. data‑plus‑behaviour.
  4. Write the type definition – Use pseudo‑code; add language‑specific syntax if helpful.
  5. Define supporting operations – Constructors, accessors, mutators, and any other methods.
  6. Test the type – Create representative instances, exercise all operations, and check edge cases.

Example A – Record (Library Book)

Design Steps

StepActionResult
1Identify entityBook – needs title, author, ISBN, availability, borrower ID.
2Choose representationRecord (fields of different primitive types).
3Define type (pseudo‑code)

type Book is record

title : string

author : string

isbn : string

isAvailable : boolean

borrowerID : integer // 0 if not borrowed

end record

4Write operations

  • function Book(title, author, isbn) → Book – constructor.
  • procedure borrow(b: in out Book, id: integer) – sets isAvailable false and stores borrowerID.
  • procedure return(b: in out Book) – resets availability.
  • procedure display(b: Book) – prints all fields.

5Test with sample dataCreate three Book instances, borrow one, return another, verify field updates.

Language‑Specific Implementations

Java

public class Book {

private String title;

private String author;

private String isbn;

private boolean isAvailable = true;

private int borrowerID = 0;

public Book(String title, String author, String isbn) {

this.title = title;

this.author = author;

this.isbn = isbn;

}

public void borrow(int id) {

if (isAvailable) {

isAvailable = false;

borrowerID = id;

}

}

public void returnBook() {

isAvailable = true;

borrowerID = 0;

}

public void display() {

System.out.println(title + " – " + author + " (ISBN: " + isbn + ")");

System.out.println(isAvailable ? "Available" : "Borrowed by " + borrowerID);

}

}

Python (dataclass)

from dataclasses import dataclass

@dataclass

class Book:

title: str

author: str

isbn: str

is_available: bool = True

borrower_id: int = 0

def borrow(self, borrower_id: int):

if self.is_available:

self.is_available = False

self.borrowerid = borrowerid

def return_book(self):

self.is_available = True

self.borrower_id = 0

def display(self):

print(f"{self.title} – {self.author} (ISBN: {self.isbn})")

print("Available" if self.isavailable else f"Borrowed by {self.borrowerid}")

What‑If Scenario

Example B – Enumerated Type (Traffic Light)

Pseudo‑code Definition

type TrafficLight is enum { Red, Amber, Green }

Language‑Specific Implementations

Java

public enum TrafficLight {

RED, AMBER, GREEN

}

Python

from enum import Enum

class TrafficLight(Enum):

RED = 1

AMBER = 2

GREEN = 3

When to Use an Enum

  • The set of possible values is known at design time and will not change.
  • Compile‑time type safety is required.
  • Typical domains: days of the week, menu choices, status codes.

Example C – Class (Book with Behaviour)

Pseudo‑code Class Definition

class Book

// attributes

title : string

author : string

isbn : string

isAvailable : boolean

borrowerID : integer

// constructor

function Book(t:string, a:string, i:string)

title := t

author := a

isbn := i

isAvailable := true

borrowerID := 0

end function

// methods

procedure borrow(id:integer)

if isAvailable then

isAvailable := false

borrowerID := id

end if

end procedure

procedure return()

isAvailable := true

borrowerID := 0

end procedure

procedure display()

output title, " by ", author, " (ISBN:", isbn, ")"

if isAvailable then

output " – Available"

else

output " – Borrowed by ", borrowerID

end if

end procedure

end class

Key OO Concepts Highlighted

  • Encapsulation: Fields are private (implicit) and accessed via methods.
  • Constructor: Guarantees a valid initial state.
  • Mutators (setters) & Accessors (getters): borrow and return modify state; display reads it.
  • Behaviour bundled with data satisfies the A‑Level OO requirement.

13.2 Information Representation

Binary, BCD, and Character Sets

  • Binary: Base‑2 representation; each digit is a bit. Example: decimal 13 → 1101₂.
  • BCD (Binary‑Coded Decimal): Each decimal digit is stored as a 4‑bit binary number.

    Example: 59 → 0101 1001 (5 = 0101, 9 = 1001).

  • ASCII: 7‑bit code for 128 characters (0–127).

    Example: 'A'0100 0001₂.

  • Extended ASCII: 8‑bit (0–255) – adds accented letters, graphics, etc.
  • Unicode: 21‑bit space; most common plane (BMP) uses 16 bits. UTF‑8 encodes Unicode code points in 1–4 bytes.

Unicode → UTF‑8 Example

Code point U+1F600 (😀) = binary 0001 1111 0110 0000 0000. UTF‑8 bytes:

  1. 11110xxx → 11110000
  2. 10xxxxxx → 10011111
  3. 10xxxxxx → 10011000
  4. 10xxxxxx → 10000000

Practice Exercise

Convert the Unicode code point U+00E9 (é) to UTF‑8 bytes.

13.3 Communication & Networks

Network Types & Topologies

NetworkTypical SpeedMediaCommon Devices
LAN (Local Area Network)10 Mbps – 10 GbpsTwisted‑pair, fibre, Wi‑FiSwitches, routers, NICs
WAN (Wide Area Network)56 kbps – 1 GbpsCoax, fibre, satelliteModems, routers

Topologies

  • Star: All nodes connect to a central switch/hub.
  • Bus: All nodes share a single communication line (rare today).
  • Ring: Nodes form a closed loop; token passing controls access.
  • Mesh: Multiple redundant paths – used for high‑availability networks.

Ethernet Frame Structure & CSMA/CD

| Preamble (7 bytes) | SFD (1 byte) | Destination MAC (6 bytes) |

| Source MAC (6 bytes) | Type/Length (2 bytes) | Data (46‑1500 bytes) |

| CRC (4 bytes) |

CSMA/CD (Carrier Sense Multiple Access with Collision Detection) lets devices listen before transmitting; if a collision occurs, they wait a random back‑off time before retrying.

IP Addressing & Subnetting

  • IPv4 address: 32 bits, written as four octets (e.g., 192.168.1.10).
  • Subnet mask determines the network portion. Example: /24 (255.255.255.0) leaves 8 bits for hosts → 2⁸‑2 = 254 usable addresses.

Subnetting Exercise

Given the network 10.0.0.0/22, how many usable host addresses are available?

Domain Name System (DNS) & URLs

  • DNS translates a domain name (e.g., www.example.com) to an IP address.
  • URL structure: protocol://host:port/path?query#fragment.

Cloud Computing Models

ModelWhat is ProvidedTypical Example
IaaS (Infrastructure as a Service)Virtual machines, storage, networkingAmazon EC2, Microsoft Azure VMs
PaaS (Platform as a Service)Runtime environment, middleware, databasesGoogle App Engine, Heroku
SaaS (Software as a Service)Fully functional applicationsGoogle Workspace, Microsoft 365

Security Implications of Cloud Services

  • Data residency & compliance.
  • Shared‑responsibility model – provider secures infrastructure, you secure data and access controls.

13.4 Hardware Fundamentals

Core Components

  • CPU: Executes instructions; contains ALU, registers, control unit.
  • Memory: RAM (volatile), ROM (non‑volatile), Cache (fast SRAM).
  • Input/Output: Keyboard, mouse, display, storage devices.

SRAM vs. DRAM

CharacteristicSRAMDRAM
Cell structure6 transistors (no capacitor)1 transistor + 1 capacitor
Access time~10 ns (fast)~50‑100 ns (slower)
DensityLow (fewer cells per chip)High (compact cells)
Power consumptionHigher (continuous power)Lower (needs refresh)
Typical useCPU cacheMain memory

Embedded Systems

Specialised computers built into devices (e.g., microwaves, automotive controllers). Characteristics: limited resources, real‑time constraints, often use microcontrollers with integrated RAM/ROM.

13.5 Processor Fundamentals

CPU Architecture & Fetch‑Execute Cycle

  1. Fetch: Retrieve instruction from memory (address in PC).
  2. Decode: Identify operation and required operands.
  3. Execute: Perform operation via ALU or control unit.
  4. Store: Write result back to register or memory.
  5. Update PC: Point to next instruction.

Interrupts

  • Hardware or software signals that temporarily suspend the current instruction sequence.
  • CPU saves the current state (program counter, registers) and jumps to an interrupt‑service routine (ISR).

Pipelining

A 5‑stage pipeline (IF, ID, EX, MEM, WB) allows overlapping of instruction phases, increasing throughput.

  • Hazards:

    • Data hazard – an instruction depends on the result of a previous one.

    • Control hazard – branch instructions change the flow.

    • Structural hazard – hardware resources are insufficient.

  • Techniques such as forwarding, stalling, and branch prediction mitigate hazards.

Parallelism & Amdahl’s Law

Speed‑up = 1 / [(1‑P) + P / S] where P is the proportion of the program that can be parallelised and S is the speed‑up of the parallel portion. Demonstrates diminishing returns as P approaches 1.

13.6 System Software

Operating System Functions

  • Process management (creation, scheduling, termination).
  • Memory management (allocation, paging, segmentation).
  • File system handling.
  • Device control and I/O.

Process Scheduling Algorithms

AlgorithmKey IdeaTypical Use
FCFS (First‑Come‑First‑Served)Run processes in arrival order.Batch systems.
Round‑Robin (RR)Each process gets a fixed time‑slice (quantum).Time‑sharing, interactive systems.
Shortest‑Job‑First (SJF)Run the process with the smallest CPU burst first.Minimise average waiting time (non‑preemptive).
Priority SchedulingHigher‑priority processes run first.Real‑time or mixed‑criticality systems.

Language Translators & IDEs

  • Compiler: Translates source code to object code before execution.
  • Interpreter: Executes source code line‑by‑line.
  • IDE: Integrated Development Environment – combines editor, compiler/interpreter, debugger, and build tools.

13.7 Security & Privacy

Common Threats

  • Malware (virus, worm, Trojan, ransomware).
  • Social engineering (phishing, pretexting).
  • Network attacks (DoS, man‑in‑the‑middle, eavesdropping).

Cryptographic Hash Functions

  • Produce a fixed‑size digest from any input (e.g., SHA‑256 → 256‑bit hash).
  • Properties: deterministic, fast to compute, pre‑image resistance, avalanche effect.
  • Used for data integrity checks and password storage (with salting).

Checksum Exercise

Compute the simple 8‑bit checksum for the byte sequence 0x12, 0xAF, 0x34 by summing the bytes modulo 256.

13.8 Ethics & Ownership

Key Issues

  • Intellectual property – copyright, patents, trademarks.
  • Software licences – proprietary, open‑source (GPL, MIT, Apache).
  • Privacy – data protection regulations (GDPR, Data Protection Act).
  • Impact of AI and automation on employment and society.

Case Study: Open‑Source vs. Proprietary in a School

A secondary school must choose a learning‑management system. Discuss the advantages of using an open‑source solution (cost, customisation, community support) against a proprietary product (vendor support, guaranteed updates). Conclude with a justified recommendation.

13.9 Databases

Core Concepts

  • Database: Structured collection of related data.
  • DBMS: Software that creates, reads, updates, and deletes data (CRUD).
  • Data Model: Relational – tables (relations) with rows (records) and columns (fields).

Data Definition Language (DDL)

  • CREATE TABLE – defines a new table and its fields.
  • ALTER TABLE – modifies structure (add/drop column).
  • DROP TABLE – removes a table.

Data Manipulation Language (DML)

  • INSERT INTO – adds a new record.
  • SELECT – queries data.
  • UPDATE – modifies existing records.
  • DELETE – removes records.

SQL Example – Student Results

CREATE TABLE ExamResult (

studentID INT PRIMARY KEY,

name VARCHAR(50),

mark1 INT,

mark2 INT,

mark3 INT

);

INSERT INTO ExamResult VALUES (101, 'Alice', 85, 90, 78);

SELECT studentID, name,

(mark1 + mark2 + mark3) / 3.0 AS average

FROM ExamResult;

13.10 Testing Strategies for User‑Defined Types

Unit Testing

  1. Test each operation in isolation (e.g., borrow() on a fresh Book).
  2. Include normal, boundary, and error cases.

Constructor Tests

  • Verify that all fields receive the intended initial values.
  • Check that invalid arguments are handled (e.g., empty title).

Edge‑Case Data

  • Empty strings, maximum/minimum integer values, special characters.
  • For enums, attempt to assign an illegal value (should be caught at compile time).

Integration Test

Write a small driver program that stores several objects (e.g., a list of Book records) in an array or collection, performs a sequence of operations, and checks the final state.

13.11 Practice Question – Design a Student Exam Result Type

Requirements

  • Student ID (integer)
  • Name (string)
  • Marks for three subjects (array of three integers)
  • Method to calculate the average mark.

Design Steps

  1. Identify entity: ExamResult.
  2. Attributes:

    • studentID : integer
    • name : string
    • marks : array[1..3] of integer

  3. Choose representation: Record (data aggregation) – behaviour limited to a single average calculation.
  4. Define type (pseudo‑code):

    type ExamResult is record

    studentID : integer

    name : string

    marks : array[1..3] of integer

    end record

  5. Operation – average:

    function average(r: ExamResult) : real

    total := 0

    for i from 1 to 3 do

    total := total + r.marks[i]

    end for

    return total / 3.0

    end function

  6. Testing plan:

    • Create an instance with marks {85, 90, 78}; verify average returns 84.33.
    • Boundary test: marks {0, 0, 0} → average 0; marks {100, 100, 100} → average 100.
    • Check that the record stores the ID and name unchanged after calling average.

Java Implementation

public class ExamResult {

private int studentID;

private String name;

private int[] marks = new int[3];

public ExamResult(int id, String name, int[] marks) {

this.studentID = id;

this.name = name;

System.arraycopy(marks, 0, this.marks, 0, 3);

}

public double average() {

int total = 0;

for (int m : marks) total += m;

return total / 3.0;

}

// getters omitted for brevity

}

Python Implementation (dataclass)

from dataclasses import dataclass

from typing import List

@dataclass

class ExamResult:

student_id: int

name: str

marks: List[int] # expects three integers

def average(self) -> float:

return sum(self.marks) / 3.0

13.12 Summary Checklist

  • Have I identified all relevant attributes of the real‑world entity?
  • Is the chosen representation (enum, record, or class) the most appropriate?
  • Are field types compatible with the data they will hold?
  • Did I provide constructors, accessors, mutators, or other necessary operations?
  • Have I written a simple test plan covering normal and edge cases?
  • Can a future change (e.g., adding a field) be made by editing only the type definition?
  • Do I understand the related syllabus topics (information representation, networking, hardware, etc.) that may affect my design?