F166: Software Development Revision Notes

OCR AAQ Computing H129   Optional NEA unit, 70 GLH   Topic Areas 1 to 5

Free revision notes for OCR Cambridge Advanced National in Computing: Application Development unit F166 Software development (Extended Certificate H129). They cover all five Topic Areas in the specification: fundamentals of software development, then designing, creating, testing, and reviewing software solutions.

F166 is an optional unit assessed by an OCR-set assignment (NEA), not an exam. The assignment has 24 assessment criteria across three tasks, and they ask you to apply the knowledge in these notes. Code examples are in C#; the specification does not name a programming language. Source: the OCR specification (version 6.0, October 2026, section 5.3.5).

Topic 1 - Fundamentals of software development

1.1  Software design principles: stepwise refinement, decomposition and modularity

The spec lists seven software design principles. For each one you need its features and how it affects the way software is designed.

Decomposition
Breaking a problem down into smaller sub-problems that can each be solved separately. An order system splits into customers, stock, invoices and reports.
Impact: each sub-problem becomes a part of the design that can be written, tested and fixed on its own, and shared between developers.
Stepwise refinement
A top-down method: start with a short statement of the whole solution, then repeatedly break each step into more detailed steps until every step is simple enough to code directly.
Impact: the design is produced in levels, so each level can be checked before detail is added.
Modularity
Building the solution from separate, self-contained modules, each with one job and a clear interface (what goes in, what comes out).
Impact: modules can be developed, tested, replaced and reused independently. A change inside one module does not break the others if its interface stays the same.
Maintainability
How easily the software can be understood, corrected, adapted and extended after it is written, often by someone else.
Impact: the design uses meaningful names, comments, consistent indentation, small modules, constants in place of repeated values, and version control (see 3.2).
LevelStepwise refinement of "produce an invoice"
1Produce an invoice
2Get the customer. Get the items ordered. Work out the total. Output the invoice.
3"Work out the total" becomes: set total to 0; for each item, add its price to the total; add the delivery charge.

Decomposition is the act of splitting a problem into parts. Stepwise refinement is the repeated process of adding detail level by level. D2 asks you to assess how far your design applies the principles, and the guidance requires at least three of them.

1.1  Software design principles: abstraction

Abstraction is hiding or removing unnecessary detail so that only what matters for the task is left. The spec names three kinds.

Functional abstraction
Hides how a task is carried out behind a named procedure or function. The caller only needs its name, its parameters and what it returns. Math.Sqrt(x) can be used without knowing the method it uses.
Data abstraction
Hides how data is stored behind the operations that use it. A stack is used through push and pop, whether it is built on an array or a linked list. A class with private fields and public methods does the same.
Control abstraction
Hides how the flow of control is carried out. A foreach loop states "repeat for every item" and hides the counter, the end test and the jump back that the processor actually performs.

Impact on design: designs can be drawn at a high level first (a Level 0 data flow diagram is an abstraction of the whole system), complex parts can be treated as "black boxes", and the inside of a part can change without affecting the rest.

1.1  Software design principles: OOP and encapsulation

Object-Orientated Programming (OOP) designs a solution as a set of objects that each hold their own data and the code that works on it. An object is created from a class, which acts as the template. Classes can inherit from other classes, so shared features are written once.

Encapsulation is bundling data and the code that works on it into one unit, and restricting access to it from outside. Other code uses the unit through its interface and cannot change its data directly. The spec lists the units that encapsulate code:

Modules
A self-contained unit of code, often a separate file, that groups related routines. In C# a class file or a namespace does this job.
Procedures
A named block of code that carries out a task and does not return a value. In C# a void method.
Functions
A named block of code that returns a value to the code that called it.
Classes
A template for objects. Properties are the data each object holds (a record's title and price). Methods are the actions it can carry out (describe itself, apply a discount).

Impact on design: OOP suits solutions with many things of the same kind (customers, stock items, orders). Encapsulation protects data from accidental change, puts validation in one place, and means a routine is written once and called many times. See 3.1.5 for the C# syntax.

D3 is awarded for encapsulation that improves the efficiency of the software solution. Code that is repeated in several places and then moved into one function or class is the clearest case.

1.2  Programming language types

TypeFeatures and characteristicsExamples
ProceduralThe program is a sequence of instructions, grouped into procedures and functions that are called in order. Data is held separately from the procedures that act on it.C, Pascal, BASIC
Object orientationThe program is built from objects created from classes. Each object combines data (properties) and behaviour (methods). Uses encapsulation, inheritance and polymorphism.C#, Java, C++
FunctionalThe program is built from functions that take inputs and return outputs without changing any stored state. Data is not modified after it is created, and recursion often replaces loops.Haskell, F#, Erlang
ScriptingUsually interpreted line by line when run, with no separate compile step. Often runs inside another program (a browser, an operating system shell) to automate or control it.JavaScript, Python, PHP, Bash, PowerShell
TypeAdvantagesDisadvantagesWhen it is appropriate
ProceduralSimple to learn and to follow from top to bottom. Little overhead, so programs are small and fast.Data is often shared by many procedures, so a change can have unexpected effects. Harder to maintain and reuse as the program grows.Small programs and tasks with a clear sequence of steps.
Object orientationClasses can be reused and extended. Encapsulation protects data. Modular, so large teams can work on separate classes.Needs more design before coding. More code than a small task needs. Takes longer to learn.Large or long-lived systems with many related things to model, graphical interfaces, games.
FunctionalNo changing state, so functions are predictable and easy to test. Well suited to running tasks in parallel.An unfamiliar style for many developers. Input, output and stored state are harder to express.Data processing and transformation, mathematical and financial calculations, concurrent systems.
ScriptingQuick to write, change and test. Runs on any platform that has the interpreter.Runs more slowly than compiled code. Many errors are only found when the line runs. The interpreter must be installed.Automating tasks, web pages, prototypes, joining other programs together.

Differences: procedural code is organised around procedures, object-orientated code around objects, and functional code around functions with no stored state. Scripting describes how the code is run (interpreted, inside a host) more than how it is organised. The types overlap: C# is mainly object-orientated but also allows procedural and functional styles, and Python is both a scripting and an object-orientated language.

When a question or criterion asks why a language type is appropriate, link a feature to the scenario: "an order system has customers, stock items and orders, so classes model them directly" is a reason; "OOP is modern" is not.

Topic 2 - Design software solutions

2.1.1  Software Design Specifications (SDS)

A Software Design Specification (SDS) is the document that states what the software solution must do, written before the solution is designed.

Purpose and use
Records what the client and developer have agreed. It is the starting point for the designs in the SDD, the source of the tests in the test plan, and the list the finished solution is reviewed against.
Format, layout and templates
A template with fixed headings, a title, author, date and version, numbered sections and numbered requirements, often in tables. A consistent format means nothing is missed, the client can check it, and every requirement can be traced to a design and a test by its number.

Content of an SDS (spec list):

SectionWhat it containsExample (a school library loans system)
Solution overviewA summary of the problem, the client and users, and the objectives of the solution: what it will do.The system will store members and books, record loans and returns, and list overdue loans.
Client requirementsWhat the client has asked for, expanded into specific statements that can be checked.CR3: the librarian can see every loan that is more than 14 days old.
Functional requirementsWhat the solution must do: its functions, inputs, processing and outputs.FR5: the system rejects a loan if the member already has five books.
Non-functional requirementsHow well it must do it: qualities such as usability, performance, security, reliability and accessibility.NFR2: every screen can be reached from the main menu in one step.
ConstraintsLimits the design has to work within.Must run on the library's existing Windows PC.

How format affects effectiveness: a requirement written as "the system should be easy to use" cannot be designed for or tested. "Every screen can be reached from the main menu in one step" can. Numbering lets Task 3 say exactly which requirements were met.

P1 is the solution overview: the guidance says to extract the specific objectives from the scenario. P2 is the client requirements, expanded into specific requirements that can be used as criteria to review against in Task 3. Both must be in an SDS.

2.1.1  How requirements and constraints impact the design

Functional requirements
Decide what the design contains: each one leads to processes on the data flow diagram, data that must be stored, inputs and outputs on the interface, and algorithms. "Produce an invoice" needs customer and order data, a calculation and an output layout.
Non-functional requirements
Decide how the design does it. "Used by someone with limited computer experience" leads to a simple menu, clear labels and helpful error messages. "Data must not be lost" leads to file backups. "Only staff can use it" leads to a password check.

Constraints limit the choices open to the designer. The spec's examples:

ConstraintHow it can impact the design
AudienceThe users' age, experience and needs set the interface style, wording, text size and amount of help.
BudgetLimits development time, paid tools, libraries and hardware, so features may be reduced.
Client requirementsThe client may fix the scope or insist on a feature or layout, ruling out alternatives.
External dependenciesLibraries, files, services or other systems the solution relies on. Their formats and availability must be designed around.
Hardware limitationsProcessor speed, memory, storage, screen size and input devices limit data volumes and interface layout.
Industry standardsAgreed formats, coding standards and accessibility guidelines the design is expected to follow.
Language limitationsWhat the chosen programming language and its libraries can and cannot do.
Organisational policiesThe client's own rules, such as password rules, data retention, approved software and branding.
Technical requirementsThe operating system, file formats or existing systems the solution must work with.
TimeThe deadline limits how many features can be designed, built and tested.

M1 is to explain how the functional and non-functional requirements impact the design. D1 needs at least three constraints, each with an explanation of how it would impact the design. Write "because of X, the design does Y".

2.1.2  Software Design Documentation (SDD) components

Software Design Documentation (SDD) is the set of designs that show how the solution will be built to meet the SDS. A developer should be able to build the solution from it. The spec lists five components.

SDD componentPurposeSoftware design tool
Data structure designShows what data is stored and how: files, records, fields, data types, sizes, keys and validation, and the structures used in memory.Data structure design tables (a data dictionary)
Data flow diagramsShow how data moves into, around and out of the system. Level 0 and Level 1.Data flow diagrams
Architectural designShows the overall structure: the modules or components and how they connect.Often a structure chart or block diagram
Interface designShows what the user sees and how they move through it.Navigation diagram, wireframe, visualisation diagrams
Algorithm designsShow the steps the code will follow for input, process, storage and output.Flowchart, pseudocode

Architectural design can include (spec examples): external components the solution relies on, such as libraries and data files; component interfaces, meaning the parameters each component takes and what it returns; module/component interactions, meaning which module calls which and what data passes between them; and component-level design, the internal design of each component.

M2 is to explain how each design (data structure, interface, data flow and algorithms) relates to the requirements in the SDS. Refer to requirements by number: "the Loans file design stores the date borrowed, which FR6 needs to find overdue loans".

2.1.2  Data structure design

A data structure design shows how the data will be stored. One table per file or record type is the usual layout:

FieldData typeSize or formatValidationExample
memberId (key)Integer1 to 9999Unique, generated by the system1042
surnameStringUp to 30 charactersPresence checkOkafor
emailStringUp to 60 charactersFormat check: contains @a.okafor@example.com
booksOnLoanInteger0 to 5Range check2
activeBooleantrue or falseType checktrue

The design also states the file each record is saved in and its layout (for example one record per line with fields separated by commas), how records in different files are linked (the Loans file stores a memberId), and any in-memory structures such as an array of records or a queue (see 3.1.7).

The P3 guidance says the data structure design must show how the data will be stored and must have enough detail to be interpreted by someone who hasn't seen it before. Give every field a data type.

2.1.2  Data flow diagrams: Level 0 and Level 1

A data flow diagram (DFD) shows where data comes from, where it goes, where it is stored and which processes change it. It does not show decisions, loops or the order of events. Symbols differ between notations; these notes use rectangles for external entities, rounded boxes for processes and open-ended boxes for data stores.

ComponentMeaningConvention
External entityA person, organisation or system outside the solution that sends or receives dataNamed with a noun: Member, Librarian
ProcessSomething that changes or uses dataNumbered and named with a verb: 2 Record loan
Data storeWhere data is held, such as a fileLabelled D1, D2 with a noun: D3 Loans. Appears from Level 1.
Data flowData moving between two componentsAn arrow labelled with the data it carries, never left blank

Level 0 (the context diagram) shows the whole system as a single process with its external entities and the data flowing in and out.

Member Librarian 0Library loanssystem membership details membership card loan details overdue report

Level 1 opens that single process into its main processes, and adds the data stores and the flows between them.

Member Librarian 1Register member 2Record loan 3Produce overduereport D1Members D2Books D3Loans membership details membership card member record loan details book details loan record overdue loans overdue report

Rules: every process has at least one flow in and one flow out. Data cannot flow directly between two external entities, between two data stores, or between an entity and a store: it must pass through a process. The diagrams must balance: every flow that crosses the system boundary at Level 0 appears, with the same external entities, at Level 1.

P4 uses the plural "data flow diagrams", and the spec lists Level 0 and Level 1. The guidance says they must show how data will flow through the software solution.

2.1.2  Interface design tools

Navigation diagram
A box for every screen or menu, joined by lines showing how the user moves between them. Shows the route from the main menu to each function and back.
Wireframe
The layout skeleton of one screen: boxes for the title, menu options, input fields, buttons and messages, with annotations. No colour or styling.
Visualisation diagram
A drawing of how the finished screen will look, with colours, fonts and sample content, annotated with the reasons for the choices.

Interface design can cover (spec examples):

AspectWhat the design states
Visual representation of interfaceWhat each screen looks like (wireframe or visualisation diagram)
Navigation between interface elementsHow the user gets from one screen or field to the next (navigation diagram)
Response timeHow quickly the solution should react to an action, and what the user sees while they wait
User helpOn-screen instructions, prompts that show the expected format, a help option
Error messagesThe wording of each message: what went wrong and what to do next
Command labellingThe wording of menu options and buttons, kept short, clear and consistent

A console (text) program still has an interface: its menus, prompts, messages and printed output are designed the same way.

2.1.2  Algorithm design tools: flowcharts and pseudocode

An algorithm is a sequence of steps that solves a problem. The spec lists algorithm designs for input (getting and validating data), process (calculations and decisions), storage (saving and loading) and output (displaying or printing results).

Flowchart symbolShapeUsed for
TerminatorRounded boxStart and Stop
Input/outputParallelogramData entered or displayed
ProcessRectangleA calculation or assignment
DecisionDiamondA question with Yes and No branches
SubroutineRectangle with double side linesA call to a procedure or function
Flow lineArrowThe order of the steps

Pseudocode writes the algorithm in structured, English-like statements that are not tied to one programming language. Conventions: one statement per line, keywords used consistently, and indentation to show what is inside each selection or loop.

total = 0
FOR each item IN order
    total = total + item.price
NEXT item
IF total > 50 THEN
    delivery = 0
ELSE
    delivery = 3.50
ENDIF
OUTPUT total + delivery

Choosing a tool: a flowchart makes branches and loops easy to see and suits short algorithms. Pseudocode is quicker to write and change, and is closer to the final code, so it suits longer algorithms.

The P3 and P4 guidance says to use at least one of the software design tools in Topic Area 2.1.2, with enough detail for the designs to be interpreted by someone who hasn't seen them before.

Topic 3 - Create software solutions

3.1.1  Variables, constants and data types

A variable is a named storage location whose value can change while the program runs. A constant is a named value that is set once and cannot change. Constants are used for fixed values such as a VAT rate, so the value is written in one place and has a meaningful name.

const double VatRate = 0.2;        // constant: set once, cannot change while the program runs
int stockId = 54;                  // integer: whole number
double price = 15.00;              // floating point: number with a fractional part
string artist = "The Police";      // string: text
bool inStock = true;               // Boolean: true or false

price = 13.50;                     // a variable can be given a new value
// VatRate = 0.25;                 // compile error: a constant cannot be assigned to
Spec data typeC# typeHoldsExample
IntegerintWhole numbers54
Floating pointdoubleNumbers with a fractional part15.99
String (or equivalent)stringText, in double quotes"The Police"
Booleanbooltrue or falsetrue

C# also has decimal, which stores money exactly and avoids the small rounding errors of floating point.

Converting between data types (also called casting) is needed because everything typed at the keyboard arrives as a string:

string typed = "17";
int id = int.Parse(typed);                  // string to integer: 17
double cost = double.Parse("4.50");         // string to floating point: 4.5
string label = id.ToString();               // integer to string: "17"
int pounds = (int)15.99;                    // floating point to integer: 15 (the fraction is cut off)
double exact = id;                          // integer to floating point: 17 (nothing is lost, so no cast)
bool isNumber = int.TryParse("abc", out int result);   // false, and no error is raised

The examples in these notes are in C#. The specification does not name a language, so use the one your centre teaches; the techniques are the same.

3.1.1  Naming conventions

A naming convention is a consistent rule for writing names, so that a name shows what it holds and names are written the same way throughout the code.

ConventionRuleExampleUse in C#
Camel caseNo spaces. The first word starts in lower case and each later word starts with a capital.stockId, customerNameVariables and parameters
Pascal case (upper camel case)As camel case, but the first word also starts with a capital.AddVat, Record, VatRateMethods, classes, properties and constants
Kebab caseAll lower case, with words joined by hyphens.stock-list.csvFile names only

Kebab case cannot be used for a variable in C#, because the hyphen is the minus operator: stock-list would be read as stock minus list.

The P10 guidance asks for a consistent and understandable naming convention for variables, constants, files, data structures and encapsulation. customerName can be interpreted by someone who hasn't seen the code; cn or x1 cannot.

3.1.2  Operators

The spec writes its arithmetical, Boolean and relational operators in pseudocode. Three of them are written differently in C#.

OperationSpecC#ExampleResult
Plus++17 + 522
Minus--17 - 512
Multiplication**17 * 585
Divide//17 / 5.03.4
Modulus (remainder)MOD%17 % 52
Quotient (whole-number division)DIV/ between two integers17 / 53
Exponentiation^Math.Pow(x, y)Math.Pow(2, 3)8
Brackets()()(17 + 5) * 244
TypeSpecC#Meaning
BooleanAND&&True only if both conditions are true
OR||True if at least one condition is true
NOT!Reverses true and false
Relational<<Less than
<=<=Less than or equal to
>>Greater than
>=>=Greater than or equal to
====Equal to
!=!=Not equal to
int a = 17, b = 5;
Console.WriteLine(a / b);             // 3     DIV: both values are int, so the result is the quotient
Console.WriteLine(a % b);             // 2     MOD: the remainder
Console.WriteLine(a / 5.0);           // 3.4   one value is a double, so this is normal division
Console.WriteLine(Math.Pow(2, 3));    // 8     exponentiation
Console.WriteLine((a + b) * 2);       // 44    brackets are worked out first

bool inRange = a >= 1 && a <= 99;     // AND: true only if both sides are true
bool outside = a < 1 || a > 99;       // OR: true if either side is true
bool rejected = !inRange;             // NOT: reverses true and false

In C# ^ is not a power operator: 2 ^ 3 gives 1, not 8. A single = assigns a value; == compares two values.

3.1.3  Selection

Selection chooses which block of code runs, depending on whether a condition is true. The spec lists If Then Else, Else If/ElseIf, End If and Case/Switch.

if (price >= 10)
{
    Console.WriteLine("Premium record");
}
else if (price >= 4)
{
    Console.WriteLine("Standard record");
}
else
{
    Console.WriteLine("Bargain record");
}

switch (menuChoice)
{
    case 1:
        Console.WriteLine("Customers");
        break;
    case 2:
        Console.WriteLine("Invoices");
        break;
    default:
        Console.WriteLine("Choose 1 or 2");
        break;
}

C# has no Then or End If keywords: the condition goes in brackets and a closing brace } ends each block. else if tests a further condition only when the ones before it were false. Case/Switch compares one value against a list of cases and is clearer than a long chain of else if when every test is on the same variable, such as a menu choice. default runs when no case matches.

3.1.4  Iteration

Iteration repeats a block of code. A fixed loop (count-controlled) repeats a known number of times. A conditional loop (condition-controlled) repeats until a condition changes.

// Fixed loop: repeats a set number of times
for (int i = 1; i <= 3; i++)
{
    Console.WriteLine("Invoice line " + i);
}

// Conditional loop, pre-condition: tested before each pass, so it can run zero times
int unpacked = 3;
while (unpacked > 0)
{
    unpacked = unpacked - 1;
}

// Conditional loop, post-condition: tested after each pass, so it always runs at least once
string answer;
do
{
    Console.Write("Add another record? (y/n): ");
    answer = Console.ReadLine();
} while (answer == "y");
Spec termC#When the condition is testedFewest times it runs
Fixed loopfor, foreachThe number of repeats is set in advance0
Conditional loop, pre-conditionwhileBefore each pass0
Conditional loop, post conditiondo ... whileAfter each pass1

P8 needs appropriate selection and iteration, so the solution functions as intended. A menu that repeats until the user chooses Exit uses both: a conditional loop around a switch.

3.1.5  Encapsulation: procedures, functions and parameter passing

Procedures and functions (both called methods in C#) give a block of code a name so it can be written once and called from anywhere. Parameters pass data in. A return value passes a result back.

// Procedure: carries out a task and returns nothing (void)
static void ShowMenu()
{
    Console.WriteLine("1 Customers");
    Console.WriteLine("2 Invoices");
}

// Function: returns a value to the code that called it
static double AddVat(double netPrice, double rate)
{
    return netPrice * (1 + rate);
}

// By value (the default): the method gets a copy, so the caller's variable is unchanged
static void DiscountByVal(double price)
{
    price = price * 0.5;
}

// By reference (ref): the method works on the caller's own variable
static void DiscountByRef(ref double price)
{
    price = price * 0.5;
}
ShowMenu();
double gross = AddVat(5.00, 0.2);     // the return value is stored: 6

double price = 10.00;
DiscountByVal(price);                 // price is still 10
DiscountByRef(ref price);             // price is now 5
Spec termC#What is passedEffect on the caller's variable
Byval (by value)The defaultA copy of the valueUnchanged
Byref (by reference)ref (or out)A reference to the variable itselfChanged by the method

Modules group related methods and classes, in C# as separate class files or namespaces. Libraries are collections of pre-written, tested routines. The .NET class library supplies predefined routines such as Console.WriteLine, Math.Round and File.Copy, brought in with a using line at the top of the file (using System.IO;).

3.1.5  Encapsulation: classes, properties, getters and setters

A class bundles data and the methods that work on it. Marking a field private hides it; a getter returns its value and a setter changes it, so the setter can refuse invalid data. In C# a property holds the getter and setter together.

class Record
{
    private double price;                  // private field: hidden from code outside the class

    public string Title { get; set; }      // property with an automatic getter and setter

    public double Price                    // property with a validation rule in its setter
    {
        get { return price; }
        set
        {
            if (value >= 0)
            {
                price = value;
            }
        }
    }

    public string Describe()               // method
    {
        return Title + " costs £" + price.ToString("0.00");
    }
}
Record single = new Record();          // an object made from the class
single.Title = "Stay With Me";         // calls the setter
single.Price = -3;                     // refused by the setter, so the price stays 0
single.Price = 3.50;
Console.WriteLine(single.Describe());  // Stay With Me costs £3.50

D3 needs encapsulation that improves the efficiency of the software solution: for example one Record class used for every stock item, or one validation function called by every input, in place of the same code written out several times.

3.1.6  File manipulation

Variables are lost when the program closes. Files keep data on storage so it is still there next time. A file is opened, read from or written to, then closed. Closing releases the file and makes sure everything written is saved.

using System.IO;

string path = "stock-list.csv";

// Writing. The using block opens the file and closes it at the closing brace,
// even after an error. The file is created if it does not exist.
using (StreamWriter writer = new StreamWriter(path))
{
    writer.WriteLine("54,1980s,The Police,Message in a Bottle,15.00");
}

// Appending (true) adds to the end of the file instead of replacing its contents
using (StreamWriter writer = new StreamWriter(path, true))
{
    writer.WriteLine("55,1980s,Gloria Estefan,Anything for You,13.00");
}

// Reading one line at a time until the end of the file
using (StreamReader reader = new StreamReader(path))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        string[] fields = line.Split(',');
        Console.WriteLine(fields[3]);           // the title
    }
}

// Managing files: copy (a backup) and delete
if (File.Exists(path))
{
    File.Copy(path, "stock-list-backup.csv", true);   // true: replace an older backup
}
File.Delete("stock-list-old.csv");                    // does nothing if the file is not there
Spec termC# (in System.IO)
Opening and closing filesnew StreamReader(path) or new StreamWriter(path) opens. The end of the using block closes, or call Close().
Reading from filesReadLine() for one line; File.ReadAllLines(path) for every line as an array
Writing to filesWriteLine(); File.WriteAllLines(path, lines) to write a whole array
Managing files: create, copy, delete, backupWriting creates the file if it is missing. File.Exists, File.Copy (a copy under another name is a backup), File.Delete

M4 is for appropriate file manipulation, so the solution functions as intended. If the scenario asks for data to be kept or backed up, the solution needs to save it, load it again when it starts, and make the backup copy.

3.1.7  Data structures

A data structure holds a collection of related items under one name.

StructureFeaturesUsed for
ArrayA fixed number of items of the same data type, each reached directly by its index. The first index is 0.A list whose size is known, such as the categories, or the lines read from a file
Linked listA chain of nodes. Each node holds an item and a link (pointer) to the next node. Grows and shrinks while the program runs. Items are reached by following the links from the start.A list with frequent insertions and removals, such as the lines of an order being built
StackLast in, first out (LIFO). Items are added (pushed) and removed (popped) at the same end, the top.Undo, or the trail of screens for a Back option
QueueFirst in, first out (FIFO). Items are added at the back (enqueued) and removed from the front (dequeued).Jobs handled in the order they arrived, such as orders waiting to be packed
// Array: fixed size, each item reached by its index, first index 0
string[] categories = { "1960s", "1970s", "1980s", "1990s" };
Console.WriteLine(categories[2]);            // retrieve: 1980s
categories[3] = "1990s and later";           // store

// Linked list: nodes joined by links, so items can be inserted or removed anywhere
LinkedList<string> orderLines = new LinkedList<string>();
orderLines.AddLast("Message in a Bottle");
orderLines.AddFirst("Stay With Me");
orderLines.Remove("Message in a Bottle");

// Stack: last in, first out (LIFO)
Stack<string> screens = new Stack<string>();
screens.Push("Main menu");
screens.Push("Customer details");
string current = screens.Pop();              // Customer details

// Queue: first in, first out (FIFO)
Queue<int> ordersToPack = new Queue<int>();
ordersToPack.Enqueue(1001);
ordersToPack.Enqueue(1002);
int next = ordersToPack.Dequeue();           // 1001

The stack, queue and linked list classes are in System.Collections.Generic. C# also has List<T>, an array-like list that can grow.

M5 asks for appropriate data structures. Choose each one for a reason that comes from the data: fixed or changing size, and the order items are needed in.

3.1.8  Other constructs: input, output, searching and sorting

ConstructSource or destinationC#
InputUser inputConsole.ReadLine(), which always returns a string
From filereader.ReadLine(), File.ReadAllLines(path)
Output from a module or procedure used as inputA return value passed straight into another call: Math.Round(AddVat(price, 0.2), 2)
OutputTo userConsole.WriteLine(), Console.Write()
To filewriter.WriteLine()
To procedure or modulePassed as an argument (parameter) in a call

Searching finds an item in a data structure. Sorting puts the items in order.

// Linear search: check each item in turn until the target is found
static int FindRecord(int[] ids, int target)
{
    for (int i = 0; i < ids.Length; i++)
    {
        if (ids[i] == target)
        {
            return i;            // the position of the match
        }
    }
    return -1;                   // not found
}

// Bubble sort: swap neighbours that are in the wrong order until a pass makes no swaps
static void SortPrices(double[] prices)
{
    bool swapped = true;
    while (swapped)
    {
        swapped = false;
        for (int i = 0; i < prices.Length - 1; i++)
        {
            if (prices[i] > prices[i + 1])
            {
                double temp = prices[i];
                prices[i] = prices[i + 1];
                prices[i + 1] = temp;
                swapped = true;
            }
        }
    }
}
AlgorithmHow it worksNote
Linear searchChecks each item in turn from the startWorks on unsorted data. Slow on long lists.
Binary searchChecks the middle item, then repeats on the half that could contain the targetMuch faster, but the data must be sorted first.
Bubble sortRepeatedly compares neighbouring items and swaps those in the wrong orderSimple to code. Slow on long lists.

The library has predefined routines for both:

int[] ids = { 17, 18, 19, 86, 54 };
double[] prices = { 5.00, 4.50, 2.50, 3.50, 15.00 };

int position = Array.IndexOf(ids, 54);    // search with a library routine: 4
Array.Sort(prices);                       // sort with a library routine: 2.5, 3.5, 4.5, 5, 15

D4 is for appropriate searching and/or sorting, so one of the two can meet it, provided the solution needs it to function as intended: finding a customer by number, or listing stock in price order.

3.1.8  Error handling: try and exception, validation rules

Error handling stops invalid data or unexpected events from crashing the program. An exception is an error raised while the program is running, such as converting "abc" to an integer or opening a file that does not exist. Code that might fail goes in a try block. If an exception is raised, the matching catch block runs and the program carries on.

int recordId = 0;
bool valid = false;
while (!valid)
{
    Console.Write("Record ID (1 to 99): ");
    string typed = Console.ReadLine();
    try
    {
        recordId = int.Parse(typed);               // "abc" throws a FormatException
        if (recordId >= 1 && recordId <= 99)       // validation rule: range check
        {
            valid = true;
        }
        else
        {
            Console.WriteLine("Enter a number from 1 to 99.");
        }
    }
    catch (FormatException)
    {
        Console.WriteLine("Enter a whole number.");
    }
    catch (OverflowException)
    {
        Console.WriteLine("That number is too large.");
    }
}

Validation rules check that data is reasonable before it is used:

Validation ruleChecks thatExample
Presence checkSomething has been enteredCustomer name is not empty
Type checkThe data is of the right data typeRecord ID is a whole number
Range checkA number is between two limitsRecord ID is from 1 to 99
Length checkThe number of characters is within limitsTelephone number has 11 digits
Format checkThe data follows a patternEmail address contains @
Lookup checkThe value is in a list of allowed valuesCategory is 1960s, 1970s, 1980s or 1990s

Validation checks that data is sensible, not that it is correct: a wrong but possible telephone number passes.

The M6 guidance is specific: error handling during user input to prevent the solution from unexpected and unintended closure. Every place the user types something needs it.

3.2  Development environments

A development environment (an Integrated Development Environment, IDE) is software that brings together the tools needed to write, run and debug code. Visual Studio, Visual Studio Code and JetBrains Rider are used for C#.

Tool (spec examples)What it does
EditorWhere the source code is typed, with line numbers and automatic indentation
AutocompleteSuggests and completes names of variables, methods and keywords as you type, reducing typing errors
Keyword highlightingColours keywords, strings and comments differently so the structure is easier to read
Syntax checkingUnderlines code that breaks the rules of the language before the program is run
Runtime environmentThe software that runs the program (for C#, the .NET runtime), so it can be run from inside the IDE
Debugging toolsRun the program under control: pause it, step through one line at a time, and see what happens
Break pointsMarkers on lines of code. The program pauses when it reaches one.
Memory inspectorShows the current values of variables and data structures while the program is paused

3.2  Version control, comments and indentation

Version control keeps a record of every version of the code. It lets a developer return to an earlier working version, see what changed and why, and avoid overwriting good code. The spec lists four things to record:

Version numberDate amendedAmended byAmends
1.002/03/2027A. StudentMain menu and customer entry
1.109/03/2027A. StudentAdded stock list loading from file
1.212/03/2027A. StudentAdded a range check to the record ID input

This can be a log kept with a numbered copy of the code for each version, the same details in the program header, or a version control tool such as Git, where each commit stores the author, date and a message.

Source code comments are notes for people reading the code. The program ignores them. The spec lists three kinds:

Program headers
A block at the top of the file: program name, purpose, author, and the version details.
Overview of purpose of code segment
A comment above a block or method saying what that section is for.
Syntax comments
A comment on a single line explaining what that statement does or why it is written that way.
// Program:       Final Vinyl order system
// Purpose:       Stores customers and stock, and produces invoices
// Version:       1.2
// Date amended:  12/03/2027
// Amended by:    A. Student
// Amends:        Added a range check to the record ID input

// Work out the invoice total                    (overview of a code segment)
double total = 0;
foreach (double linePrice in linePrices)
{
    total = total + linePrice;       // add this line to the running total   (syntax comment)
}

Source code indentation style: each block inside a method, selection or loop is indented one level further (four spaces in C#), with the braces lined up. One style is used throughout. Indentation shows which statements belong to which block.

The P9 guidance defines maintainable code as code that someone who hasn't seen it before can interpret. Its suggested evidence is the source code plus screenshots or photographs showing the use of version control, so keep the version log as you go.

Topic 4 - Test software solutions

4.1  Testing methods

Dry run / trace table
Working through the code by hand, without running it, using chosen test values. A trace table has a column for each variable and output, and a row is added each time a value changes. Finds logic errors in an algorithm.
Iterative
Testing repeatedly during creation: each procedure or feature is tested as it is finished, then fixed and retested. Finds errors early, while the code is fresh and before other code depends on it. Followed by testing of the finished solution after creation.
Test plan
A document written before testing that lists every test. OCR's template columns: test number, test type, test description, test data, expected result, actual result, remedial action required.
No.Test typeDescriptionTest dataExpected result
1ComponentRecord ID input accepts the upper boundary99Accepted
2ComponentRecord ID input rejects textabc"Enter a whole number." and the prompt repeats
3SystemStock added, program closed and reopenedOne new recordThe record is still listed

Test data follows F161 Topic 5: normal, extreme (boundary) and erroneous.

The Trace Table Generator runs C#, Python and pseudocode one line at a time and builds the trace table, which is useful for checking a dry run of a practice algorithm.

4.1  Testing types and elements to test

Testing typePurpose and featuresWhen it is appropriate
Component testingTests one component (a procedure, function, class or module) on its own, with chosen inputs and expected outputs.During creation, as each component is written
Integration testingTests that components work together: data is passed correctly between modules, and one module's output is accepted by the next.As components are joined
System testingTests the complete solution as a whole, from start to finish, in the way it will really be used.When every component has been integrated
Requirements testingTests the solution against each requirement in the SDS, to show it does what the client asked for.On the finished solution, before review

Elements of software solutions to test (spec list):

ElementWhat to check
InputValid data is accepted; validation rejects invalid data with a clear message
OutputResults are correct, complete and laid out as designed, on screen and in files
NavigationEvery menu option goes to the right place, and the user can always get back
Error handlingWrong input, missing files and other unexpected events do not close the program
Data storageData is saved, loaded correctly when the program restarts, and backed up

P5 is to describe the testing methods, the testing types and the elements you intend to test. M3 is to justify them: give a reason for each, linked to the solution. "Component testing each validation function finds input errors before they are hidden inside the menu" earns more than "component testing is useful".

4.1  Results analysis and remedial action

Results analysis compares each actual result with the expected result, identifies why any test failed and what the failure means for the user. Remedial action is the fix needed, for example "add a presence check so an empty customer name is rejected". The spec does not include carrying out the remedial action.

TestExpectedActualAnalysisRemedial action required
Empty customer name enteredRejected with a messageCustomer saved with a blank nameNo presence check on the name input, so invoices could be produced with no nameAdd a presence check to the name input and repeat the prompt

P11 needs evidence of actual results (screenshots, photographs or recordings). M7 is to analyse them and explain the remedial action; the guidance says you are not expected to fix errors found in final testing.

Topic 5 - Review and improve software solutions

5.1  Reviewing fitness for purpose

A solution is fit for purpose if it does what it was specified to do, well enough for the people who will use it. Reviewing means assessing strengths and weaknesses and comparing the solution against the requirements in the SDS. The spec lists what to judge it on:

Review againstHow to assess it
Client requirementsTake each numbered requirement from the SDS: met, partly met or not met, with evidence from testing
Functional requirementsDoes each function work, with correct results? Use the test results.
Non-functional requirementsIs it usable by the intended user, quick enough, secure enough?
MaintainabilityCould another developer understand and change it? Look at naming, comments, indentation, modular structure and the version log.
RobustnessDoes it cope with invalid input and unexpected events without closing or corrupting data? Use the error handling test results.

P12 is to assess: give a judgement for each requirement backed by evidence, covering the areas in Topic Area 5.1, including maintainability and robustness.

5.2.1  Constraints and improvements

Constraints are factors that limited the solution. The spec lists four:

Programming constructs
The constructs used, or not used, limit what the solution can do and how well. A solution built without files loses its data; one built without functions repeats code.
Language chosen
Its features, libraries and the platforms it runs on. A console program in C# has no graphical interface unless a further framework is used.
Skills of the developer
What the developer knew how to build in the time, such as classes or file handling.
Development environment
The IDE, its debugging tools, the version of the language and the hardware available.

Improvements (spec list):

ImprovementExamples
Code efficiencyReplace repeated code with a function; use a faster algorithm (binary search in place of linear search on sorted data); read a file once instead of on every search
HCI design principlesConsistent layout, clear labels, feedback after every action, fewer steps to complete a task (see F160 Topic 5)
HCI accessibility principlesReadable text size and contrast, plain wording, not relying on colour alone, keyboard access
Data exchangeImport and export in standard formats such as CSV, JSON or XML so other software can use the data (see F161 Topic 2)
SecurityPasswords stored hashed instead of as plain text, encrypted data files, different access levels, validation on every input (see F161 Topic 4)

Each improvement should be linked to a weakness found in testing or review. The spec does not include carrying the improvements out.

5.2.2  Further development opportunities

Portability of software solution
How easily the solution can be moved to other platforms: another operating system, a web version or a mobile device. Code that avoids platform-specific features and fixed file paths is more portable.
Code reusability
How far parts of the code could be used again in other programs. General-purpose functions with parameters, and classes with no scenario-specific details hard-coded, can be moved into a library and reused.

D5 is to discuss: weigh each improvement or development (benefit, cost, effort) and reach a judgement. The guidance says achieving P12 and M7 can support it.