Skip to content

9618 · Unit 12 · Paper 2: Problem-solving and programming

Software development.

9618 · Unit 12 · Software development
Revisionbyexamplicity

The program development life cycle

§12.1 · Program development life cycle · stages

Nobody builds a large program in one go. A program development life cycle divides the work of producing a program into stages: analysis, design, coding, testing and maintenance. Each stage has its own activities and its own outputs.

Analysiswhat must it do?Designhow will it work?Codingwrite the programTestingdoes it work?Maintenancekeep it usefulthe cycle starts again when maintenance can no longer keep the program fit for purpose
Analysiswhat must it do?Designhow will it work?Codingwrite the programTestingdoes it work?Maintenancekeep it usefulReturn to analysis when maintenance is insufficient.

What happens in each stage

Each stage hands something on, and the next stage cannot start without it. Name the five stages in order, and what each one passes on.

1Analysis

What must it do?

  • Investigate the problem and the current system
  • Consult the client
passes onrequirements specification
2Design

How will it work?

  • Plan the modules, data, files and interface
  • Plan the testing
passes onstructure charts, pseudocode, test plan
3Coding

Write the program

  • Write the design in a programming language
  • Find and correct syntax errors
passes onprogram code (modules)
4Testing

Does it work?

  • Run it with planned test data
  • Compare actual results with expected results
passes ontest results, corrected code
5Maintenance

Keep it useful

  • Change it after it is in use: correct, adapt or improve it
resultupdated program
When maintenance can no longer keep the program fit for purpose, the cycle starts again at analysis.
StageWhat happensMain outputs
AnalysisThe problem and the current system are investigated and the client is consulted, to agree what the program must do.requirements specification
DesignThe solution is planned: how the program will work, its data, files, interface and testing.structure charts, pseudocode, test plan
CodingThe design is written in a programming language (implementation); syntax errors are found and corrected.program code (modules)
TestingThe program is run with planned test data and the actual results are compared with the expected results.test results, corrected code
MaintenanceThe program is changed after it is in use: to correct, adapt or improve it.updated program

Why follow a life cycle?

  • The project is easier to manage, plan and cost: the work is split into stages in a known order.
  • Each stage ends with clear deliverables, so progress can be checked before the next stage starts.

A cycle, arranged by a model

  • The arrow back to analysis makes it a cycle: when maintenance can no longer keep the program fit for purpose, a new version starts again at analysis.
  • Life cycle models (waterfall, iterative, RAD) arrange these same stages in different ways.
  • Testing is not left to the end: modules are tested as they are written, and again after every change.
Your turn

1 Which stage produces the requirements specification?

2 In which stage are the actual results compared with the expected results?

3 Give one reason for following a life cycle.

  1. 1
    analysis
  2. 2
    testing
  3. 3
    the project is easier to manage, plan and cost; or each stage ends with clear deliverables, so progress can be checked
Tick what you can do now
Exam focusName the stages exactly: analysis, design, coding (or implementation), testing, maintenance. “Development” or “programming” is not accepted as a stage name. For the purpose of a life cycle, say it makes the project easier to manage, plan and cost, with clear deliverables at the end of each stage.
Practise with s26/22 Q1(e); w24/22 Q1(a); w22/23 Q1(b)(i) (older paper: life-cycle benefit)
1 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Activities and outputs of each stage

§12.1 · Program development life cycle · stages

Watching staff at work and planning a screen layout both happen before any code is written, but in different stages. Each stage of the life cycle has its own activities, so once you know them, any activity you are given points to one stage.

The two stages with the most to learn both finish before any code is written: analysis finds out what is needed, design plans how it will work.

Analysis: find out what is needed

  • Investigate the current system (and similar systems) and the problems with it.
  • Interview managers and the staff who will use the system; run surveys or questionnaires; observe the current system in use.
  • Carry out a feasibility study; decide which life cycle to use.

Produces: the problem definition and the requirements specification; interview notes and survey results.

Design: plan how it will work

  • Algorithms: structure charts, flowcharts, pseudocode, structured English, state-transition diagrams, data-flow diagrams.
  • Data: identifier tables, data and record structures, validation rules, file or database design, E-R diagrams; class (UML) diagrams.
  • The user interface: input screens and report layouts.
  • Testing: the test strategy and the test plan.
  • The programming language, and the library routines to use.

Name the stage

Cover the Stage column, name the stage for each activity, then check.

ActivityStage
The client is interviewed about the current systemAnalysis
A feasibility study is carried outAnalysis
The requirements specification is writtenAnalysis
An identifier table is producedDesign
Record and file structures are definedDesign
A structure chart is drawnDesign
The test plan is writtenDesign
ActivityStage
An algorithm is implemented in a programming languageCoding
A compiler is used; syntax errors can occurCoding
The IDE offers auto-complete as code is typedCoding
A dry run is done with a trace tableTesting
The walkthrough method is usedTesting
The program is modified to run on new hardwareMaintenance
An error reported by users after release is correctedMaintenance

Name the requested output precisely

  • For a named design output, give a structure chart, an identifier table or a test plan.
  • Breaking a problem into modules, or specifying the program structure, is a design activity.
  • Saying only “modules” does not name a design output.
Your turn

1 Staff are observed using the current system. Which stage?

2 Input screens and report layouts are planned. Which stage?

3 The actual output of a test is recorded beside the expected output. Which stage?

4 A program is changed after release to follow a new tax law. Which stage?

  1. 1
    analysis
  2. 2
    design
  3. 3
    testing
  4. 4
    maintenance
Tick what you can do now
Exam focusMatch the activity to its stage: translating source with a compiler is coding; a dry run, walkthrough or comparison with expected behaviour is testing; changes after release, including support for new hardware, are maintenance.
Practise with w24/21 Q5(a); w25/22 Q5(a); w24/23 Q5(a); s26/21 Q3(a); s26/23 Q3(c); w24/23 Q7(a); s26/22 Q1(d)
2 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

The waterfall model

§12.1 · Program development life cycle · waterfall

When everyone knows exactly what is wanted from the start, the stages can simply follow one another. The waterfall model is the traditional, linear life cycle: work flows down from one stage to the next, like water over a series of steps.

Analysisrequirements specificationDesignstructure chart, test planCodingprogram codeTestingtested programMaintenanceDown: the result of one stage is passedto the next stage as its inputUp: more work is needed at a previousstage to complete the current stage
Analysisrequirements specificationDesignstructure chart, test planCodingprogram codeTestingtested programMaintenanceDown: pass results onward. Amber: revisit prior work.

Principles

  • The stages are done one at a time, in an agreed sequence.
  • The next stage does not start until the current stage is complete.
  • Each stage produces documents that are passed down to the next stage.

Benefits

  • Simple to understand and manage: clearly defined stages, each with specific deliverables.
  • All requirements are identified before coding, so the plan is clear.
  • Cost and completion time are more predictable.
  • Works well for small projects whose requirements are well understood and will not change.

Drawbacks

  • No working software until late in the life cycle, so it is slow to reach users and there are no early prototypes.
  • Difficult to cope with changing requirements: late changes mean returning to earlier stages.
  • The client is involved mainly at the start and the end, so it does not suit a project that needs high client involvement and feedback.
  • Modules are combined (integrated) near the end, so problems appear late.
Your turn

1 What does the arrow down from Analysis to Design carry?

2 What does an arrow going up from Coding to Design mean?

3 A client wants to try the app early and change it as they go. Give one drawback of waterfall for this client.

  1. 1
    the requirements specification: the result of one stage is the input to the next
  2. 2
    more work is needed in design to complete coding
  3. 3
    there is no working software until late, so the client cannot try it early; late changes to requirements mean going back to earlier stages
Tick what you can do now
Exam focusExplain both kinds of arrow: down — the result of one stage is the input to the next; up — more work is needed at a previous stage to complete the current stage. For a drawback in context, link it to the scenario: “no working software until late, so slower to users, so the client cannot review a working interface early”.
Practise with s26/23 Q3(b); s22/23 Q8(a), (b) (older paper: waterfall drawing and arrows)
3 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Iterative and rapid application development

§12.1 · Program development life cycle · iterative and RAD

Clients often cannot say exactly what they want until they see something working. Iterative development and RAD both produce a working prototype at an early stage and expect the requirements to change as the client sees it. They differ in how the work is organised.

Iterative: repeated cycles, each producing a more complete version

Iteration 1design, code,test, reviewVersion 1a small subsetof requirementsfeedbackIteration 2design, code,test, reviewVersion 2morerequirementsfeedbackIteration ndesign, code,test, reviewFull systemall requirementsmet
Iteration 1design · code · testVersion 1small subsetreview and feedbackIteration 2design · code · testVersion 2more requirementsreview and feedbackIteration ndesign · code · testFull systemrequirements met

RAD: prototypes built and reviewed in short cycles, in parallel, then integrated

Outlinerequirementsminimal planningmodules developed in parallel as prototypesPrototype module AClient reviewsPrototype module BClient reviewsPrototype module CClient reviewsIntegrateDeliver
Outline requirementsPrototype AClient reviewsPrototype BClient reviewsPrototype CClient reviewsIntegrateDeliver

Compare the two models

Questions ask for a principle, a benefit and a drawback of each, often set against waterfall.

IterativeRapid application development (RAD)
Principles
  • Starts with a small subset of the requirements
  • Each iteration designs, codes and tests a version
  • The version is reviewed; feedback and more requirements go into the next iteration
  • Minimal detailed planning
  • Prototypes of the modules built in parallel in short cycles, then integrated
  • The client is involved throughout; used for time-critical development
Benefits
  • A working model (prototype) is available at an early stage
  • Design faults and misunderstandings are found sooner
  • Changes to requirements cost less; smaller parts are easier to test and debug
  • Quicker development: modules worked on at the same time
  • Prototypes early for the client to review
  • Changing requirements easier to include; usable modules sooner; components can be reused
Drawbacks
  • More resources (time and people) may be needed
  • Not all requirements are known at the start, so the design may need changing
  • Hard to apply to a small program that cannot be split up
  • Difficult to estimate the cost and time; documentation often omitted
  • The client must be available throughout and may keep changing their mind
  • Only suits a system that can be split into modules

Iterative

Principles

  • Starts with a small subset of the requirements
  • Each iteration designs, codes and tests a version
  • The version is reviewed; feedback and more requirements go into the next iteration

Benefits

  • A working model (prototype) is available at an early stage
  • Design faults and misunderstandings are found sooner
  • Changes to requirements cost less; smaller parts are easier to test and debug

Drawbacks

  • More resources (time and people) may be needed
  • Not all requirements are known at the start, so the design may need changing
  • Hard to apply to a small program that cannot be split up

Rapid application development (RAD)

Principles

  • Minimal detailed planning
  • Prototypes of the modules built in parallel in short cycles, then integrated
  • The client is involved throughout; used for time-critical development

Benefits

  • Quicker development: modules worked on at the same time
  • Prototypes early for the client to review
  • Changing requirements easier to include; usable modules sooner; components can be reused

Drawbacks

  • Difficult to estimate the cost and time; documentation often omitted
  • The client must be available throughout and may keep changing their mind
  • Only suits a system that can be split into modules
IterativeRapid application development (RAD)
PrinciplesDevelopment starts with a small subset of the requirements. Each iteration designs, codes and tests a version; the version is reviewed and feedback and further requirements go into the next iteration until the system is complete.Minimal detailed planning. Prototypes of the modules are built in parallel in short cycles, then integrated. The client is involved throughout, reviewing each prototype. Used for time-critical development.
BenefitsA working model (prototype) is available at an early stage, so design faults and misunderstandings are found sooner. Changes to requirements cost less. Smaller parts are easier to test and debug.Quicker development: several modules are worked on at the same time. Prototypes early for the client to review. Changing requirements are easier to include. Usable modules are delivered sooner; components can be reused.
DrawbacksMore resources (time and people) may be needed. Not all requirements are known at the start, so the design may need changing later. Hard to apply to a small program that cannot be split up.Difficult to estimate the cost and time to complete. Documentation is often omitted. The client must be available throughout, and may keep changing their mind. Only suits a system that can be split into modules.

Iterative

Principles: Development starts with a small subset of the requirements. Each iteration designs, codes and tests a version; the version is reviewed and feedback and further requirements go into the next iteration until the system is complete.

Benefits: A working model (prototype) is available at an early stage, so design faults and misunderstandings are found sooner. Changes to requirements cost less. Smaller parts are easier to test and debug.

Drawbacks: More resources (time and people) may be needed. Not all requirements are known at the start, so the design may need changing later. Hard to apply to a small program that cannot be split up.

Rapid application development (RAD)

Principles: Minimal detailed planning. Prototypes of the modules are built in parallel in short cycles, then integrated. The client is involved throughout, reviewing each prototype. Used for time-critical development.

Benefits: Quicker development: several modules are worked on at the same time. Prototypes early for the client to review. Changing requirements are easier to include. Usable modules are delivered sooner; components can be reused.

Drawbacks: Difficult to estimate the cost and time to complete. Documentation is often omitted. The client must be available throughout, and may keep changing their mind. Only suits a system that can be split into modules.

Your turn

1 Which model develops prototype modules in parallel?

2 Give one benefit of iterative development compared with waterfall.

3 Give one drawback of RAD.

  1. 1
    RAD
  2. 2
    a working prototype is available at an early stage, whereas waterfall has no working software until late
  3. 3
    the cost and time are difficult to estimate; or the client must be available throughout
Tick what you can do now
Exam focusState a principle as what the model does: “modules are developed in parallel as prototypes”, “minimal planning”, “the client is involved at every stage”. For a benefit compared with waterfall, make it a contrast: “a prototype is available at an early stage, whereas waterfall has no working software until late”.
Practise with s26/23 Q3(b)
4 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Choosing a life cycle

§12.1 · Program development life cycle · choosing a model

No life cycle is best for every project. Choose one from the scenario: are the requirements fixed or likely to change, and how soon does the client need something working?

Each model in one small picture, with the kind of project it suits. The Choose when line is the fact you look for in a scenario.

Waterfall

each stage once, in order

Choose when: Requirements are fixed and agreed at the start.

Iterative

repeatversions grow

Choose when: Requirements are unclear or will change; a prototype is wanted early.

RAD

integrateprototypes in parallel

Choose when: A tight deadline; the system splits into modules; the client is available throughout.

Why different life cycles are needed

The choice depends on the approach the project needs:

  • requirements agreed at the start or likely to change
  • prototypes or a rapid first version needed
  • the size and complexity of the problem
  • the skills and size of the team
  • the budget, time and resources
  • how much the client can be involved

Why different life cycles are needed

The choice depends on the approach the project needs: whether the requirements are agreed at the start or likely to change; whether prototypes or a rapid first version are needed; the size and complexity of the problem; the skills and size of the team; the budget, time and resources; how much the client can be involved.

Compare the three models on the same points

Set side by side, point by point, the models show where each one is strong. The first row uses the same stage names as the life cycle.

WaterfallIterativeRAD
How the stages runanalysis, design, coding, testing: once each, in orderdesign, code, test repeated for each versiondesign, code, test for each prototype, in parallel
Requirementsall agreed at the starta subset first; more added each iterationan outline; refined from prototypes
First working softwarelate, after testinga working prototype at an early stageprototypes at an early stage
Client involvementmainly at the start and end: unsuited to high involvementreviews each versionthroughout: reviews every prototype
Changing requirementshard to include lateincluded in the next iterationincluded as prototypes are reviewed
Cost and timemost predictablemeasured iteration by iterationhardest to estimate

Waterfall

How the stages run: analysis, design, coding, testing: once each, in order

Requirements: all agreed at the start

First working software: late, after testing

Client involvement: mainly at the start and end: unsuited to high involvement

Changing requirements: hard to include late

Cost and time: most predictable

Iterative

How the stages run: design, code, test repeated for each version

Requirements: a subset first; more added each iteration

First working software: a working prototype at an early stage

Client involvement: reviews each version

Changing requirements: included in the next iteration

Cost and time: measured iteration by iteration

RAD

How the stages run: design, code, test for each prototype, in parallel

Requirements: an outline; refined from prototypes

First working software: prototypes at an early stage

Client involvement: throughout: reviews every prototype

Changing requirements: included as prototypes are reviewed

Cost and time: hardest to estimate

WaterfallIterativeRAD
Requirementsall agreed at the starta subset first; more added each iterationan outline; refined from prototypes
First working softwarelate, after testinga working prototype at an early stageprototypes at an early stage
Client involvementmainly at the start and end: unsuited to high involvementreviews each versionthroughout: reviews every prototype
Changing requirementshard to include lateincluded in the next iterationincluded as prototypes are reviewed
Cost and timemost predictablemeasured iteration by iterationhardest to estimate

Justify a choice from the scenario

Each choice is a chain: a fact from the scenario, the feature of the model, the result.

Ticket app: early launch

1
A launch deadline is fixed; features will change as users try the app.
2
RAD develops prototype modules in parallel and reviews them with users.
3
Usable modules arrive sooner; feedback can change later prototypes.

Museum app: unsettled interface

1
The museum cannot yet describe the interface it needs.
2
Iterative development produces an early prototype for review.
3
Feedback shapes the next version as requirements become clearer.

Weighing machine: fixed rules

1
The agreed rules are fixed by regulation for this project.
2
Waterfall agrees requirements before coding and follows defined stages.
3
The fixed scope supports more predictable cost and completion estimates.
Your turn

1 A bank’s interest rules are set by law and will not change. Which model fits, and why?

2 A start-up needs a working app in six weeks and expects to change features after users try it. Which model fits, and why?

3 An answer says only that RAD is faster. Why does it earn little?

  1. 1
    waterfall: the requirements can be agreed at the start, so cost and time are more predictable
  2. 2
    RAD: prototype modules are built in parallel, so usable modules arrive quickly, and users review each prototype
  3. 3
    it is not linked to the scenario: say which fact in the scenario makes speed matter
Tick what you can do now
Exam focusLink each reason to the scenario: “the requirements are likely to change, so an iterative model lets each version be reviewed and changed”. A list of the model’s features with no link to the program in the question earns little.
Practise with s25/22 Q1(a)(i); s26/23 Q3(b)
5 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Structure charts: purpose and symbols

§12.2 · Program design · structure charts

Once a problem is split into modules, the team needs a map of how they fit together. A structure chart shows the modules of a program, which module calls which, and the parameters passed between them.

Purpose of a structure chart

  • Drawn at the design stage, it shows how a problem is broken down into modules: the hierarchy of modules, which module calls which, and any selection or repetition of calls.
  • It shows the parameters passed between modules (the interface), and so whether each module is a function or a procedure.

The seven symbols

Every symbol carries one fact about how the modules work together, so each must be drawn exactly.

SymbolMeaning
QuizAskModule (a procedure or a function). A line joins a module to each module it calls: the calling module is above, the called module below.
QNumA parameter passed down to the called module (by value).
AnswerA value passed back up to the calling module: the return value, so the called module is a function.
CorrectA filled circle marks a flag: a BOOLEAN value, passed down or returned.
ScoreA two-way arrow: the parameter is passed BYREF. Its value goes down and the changed value comes back up.
MainSubASubBSelection (diamond): the module calls one of the modules below; which one is decided when the program runs.
MainSubASubBIteration (curved arrow): the module repeatedly calls the modules below, in order from left to right.

Module

QuizAsk

Module (a procedure or a function). A line joins a module to each module it calls: the calling module is above, the called module below.

Data passed down

QNum

A parameter passed down to the called module (by value).

Return value

Answer

A value passed back up to the calling module: the return value, so the called module is a function.

Boolean flag

Correct

A filled circle marks a flag: a BOOLEAN value, passed down or returned.

By reference

Score

A two-way arrow: the parameter is passed BYREF. Its value goes down and the changed value comes back up.

Selection

MainSubASubB

Selection (diamond): the module calls one of the modules below; which one is decided when the program runs.

Iteration

MainSubASubB

Iteration (curved arrow): the module repeatedly calls the modules below, in order from left to right.

The last two symbols are the hardest to read. In the Quiz chart they mean:

Selection in Feedback

The diamond chooses Praise or ShowHint when the program runs.

Iteration in Quiz

The curved arrow repeats Ask, then Check, then Feedback in that order.

Your turn

1 Function GetMark is called by module Report. Which way does the arrow for its return value point?

2 What does a filled circle on a parameter arrow show?

3 A parameter arrow has a head at both ends. How is that parameter passed?

  1. 1
    up, from GetMark to Report: a return value goes back to the calling module
  2. 2
    a flag: a BOOLEAN value
  3. 3
    BYREF: its value goes down and the changed value comes back up
Tick what you can do now
Exam focusTo explain a diamond or a curved arrow, name the construct (selection or iteration) and every module involved, in order: “Quiz repeatedly calls Ask, then Check, then Feedback”. For selection, name the caller and all alternative modules.
Practise with s25/23 Q6(c); w25/22 Q7(a); w24/21 Q7(b); s24/21 Q7(b)(i)
6 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Constructing a structure chart

§12.2 · Program design · structure charts

A program described in words hides its shape: which module calls which, and what passes between them. A chart shows it at a glance. Build it in order: a box for each module, a line for each call, then an arrow for every parameter.

The notes are the quiz program; the steps turn them into a chart. Work through the steps with the notes beside you, then compare your chart with the one below.

Program notes

  • Quiz repeatedly calls Ask, then Check, then Feedback.
  • Ask takes the question number QNum and returns the Answer typed (a STRING).
  • Check takes QNum and Answer and returns Correct (a BOOLEAN).
  • Feedback takes Correct, QNum and Score (passed by reference). It calls either Praise or ShowHint.
  • Praise takes Score by reference; ShowHint takes QNum.

Steps

1
Draw a box for each module, in levels: callers above the modules they call.
2
Join each caller to every module it calls.
3
Add an arrow beside the line for each parameter, labelled with its name: down for a value passed in, up for a return value, two-way for BYREF.
4
Use a filled circle for a BOOLEAN, an open circle for other data.
5
Add the diamond or curved arrow under the module that selects or repeats.

The Quiz chart

Each branch keeps one colour. Check every arrow against the program notes.

QuizAskCheckFeedbackQNumAnswerQNumAnswerCorrectCorrectQNumScorePraiseShowHintScoreQNumKeydata passed down (parameter)BOOLEAN flag, here returnedparameter passed BYREF
Hierarchy and control; parameter views belowQuizAskCheckFeedbackPraiseShowHintRepeat Ask, then Check, then Feedback.Quiz calls Ask: parameter viewQuizAskQNumAnswerQuiz calls Check: parameter viewQuizCheckQNumAnswerCorrectQuiz calls Feedback: parameter viewQuizFeedbackCorrectQNumScoreFeedback selects one child at run time.FeedbackPraiseScoreShowHintQNum
  • Ask returns Answer to Quiz, which passes it to Check.
  • Check returns Correct, which then controls Feedback.
  • The two BYREF links pass the same Score through Feedback to Praise, so an increment reaches Quiz rather than being lost in a local copy.
Ask returns Answer to Quiz, which passes it to Check. Correct then controls Feedback. The two BYREF links pass the same Score through Feedback to Praise, so an increment is reflected in Quiz rather than lost in a local copy.
Your turn

1 Which modules can Feedback call, and how is one chosen?

2 Which parameter does Quiz pass to Feedback BYREF?

3 Check returns Correct. Why is the circle on its arrow filled?

  1. 1
    Praise or ShowHint: one of them, chosen when the program runs (selection, the diamond)
  2. 2
    Score
  3. 3
    Correct is a BOOLEAN, a flag
Tick what you can do now
Exam focusLabel every arrow with its parameter name and point it the right way: a function’s return value goes up, a BYREF parameter is two-way. Put the diamond or the curved arrow only under the module that selects or repeats.
Practise with s24/23 Q7(b); w24/21 Q7(a); w25/21 Q7(b); w25/23 Q7(b)
7 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

From structure chart to pseudocode

§12.2 · Program design · callers and interfaces

A finished structure chart already gives you most of the code's first lines. Each box on the chart becomes a module, and its arrows decide the header: FUNCTION or PROCEDURE, and which parameters are BYREF.

Read each rule on the left, then find it in the code: every one ends with the module where it shows in Quiz or Feedback.

Each box becomes a module; read each symbol as code

  • An arrow up (a value returned): FUNCTION … RETURNS type, used in an expression: Ask, Check.
  • No single return arrow up: PROCEDURE, run with CALL: Quiz, Feedback, Praise, ShowHint.
  • A two-way arrow: a BYREF parameter of a procedure: Score. Other parameters are passed by value, the default; BYVAL may be written.
  • A filled circle: the value is BOOLEAN: Correct.
  • A diamond: an IF (or CASE) chooses which module to call: in Feedback.
  • A curved arrow: a loop around the calls, made left to right: the FOR loop in Quiz.
Pseudocodeselection and iteration
PROCEDURE Quiz()
DECLARE QNum, Score : INTEGER
DECLARE Answer : STRING
DECLARE Correct : BOOLEAN
Score ← 0
FOR QNum ← 1 TO 3
Answer ← Ask(QNum)
Correct ← Check(QNum, Answer)
CALL Feedback(Correct, QNum, Score)
NEXT QNum
OUTPUT "Score: ", Score
ENDPROCEDURE

PROCEDURE Feedback(Correct : BOOLEAN,
QNum : INTEGER,
BYREF Score : INTEGER)
IF Correct = TRUE THEN
CALL Praise(Score)
ELSE
CALL ShowHint(QNum)
ENDIF
ENDPROCEDURE
Your turn

1 Ask has an arrow up for Answer, a STRING. Write its header.

2 Praise has a two-way arrow for Score. Write its header.

3 Why is Feedback run with CALL and Check is not?

  1. 1
    FUNCTION Ask(QNum : INTEGER) RETURNS STRING
  2. 2
    PROCEDURE Praise(BYREF Score : INTEGER)
  3. 3
    Feedback has no return arrow up, so it is a procedure and is run with CALL; Check returns a value, so it is a function used in an expression: Correct ← Check(QNum, Answer)
Tick what you can do now
Exam focusA returned value requires FUNCTION and RETURNS. A two-way parameter uses BYREF in the called procedure's header. Use CALL for procedures; use a function's result in an expression.
Practise with s25/23 Q6(b); w25/22 Q7(b); s25/23 Q6(a)
8 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Implementing and tracing the called modules

§12.2 · Program design · return values and BYREF effects

Once the quiz modules are written, a trace shows whether they really pass data the way the chart planned. Run the quiz with three answers and follow Score: Praise adds 1 to it BYREF, so the change reaches Quiz.

Ask returns the typed answer and Check returns a BOOLEAN. Key and Hint are the global arrays below.

Pseudocodethe other modules
FUNCTION Ask(QNum : INTEGER) RETURNS STRING
DECLARE Answer : STRING
OUTPUT "Question ", QNum
INPUT Answer
RETURN Answer
ENDFUNCTION

FUNCTION Check(QNum : INTEGER,
Answer : STRING) RETURNS BOOLEAN
RETURN TO_UPPER(Answer) = Key[QNum]
ENDFUNCTION

PROCEDURE Praise(BYREF Score : INTEGER)
Score ← Score + 1
OUTPUT "Correct"
ENDPROCEDURE

PROCEDURE ShowHint(QNum : INTEGER)
OUTPUT "Hint: ", Hint[QNum]
ENDPROCEDURE

// main program
CALL Quiz()

Original quiz data

QNumKeyHint
1RAMmain memory
2CPUit executes instructions
3ROMread-only memory

Score after Feedback

QNumAnswerCorrectScore
1ramTRUE1
2GPUFALSE1
3RomTRUE2
Console output
Question 1
Correct
Question 2
Hint: it executes instructions
Question 3
Correct
Score: 2

Trace the run

Each call has three things to watch: what goes in, what comes back, and what changes Score.

One pass, statement by statement: QNum = 1
The label on the left is the module that runs the statement.
LineStatement that runsQNumAnswerCorrectScoreOutputWritesWhat happens
QuizFOR QNum ← 1 TO 31QNum 1the first pass
the first pass
QuizAnswer ← Ask(QNum)"ram"Answer "ram"Ask outputs "Question 1", inputs ram and returns it
Ask outputs "Question 1", inputs ram and returns it
QuizCorrect ← Check(QNum, Answer)TRUECorrect TRUECheck returns TO_UPPER("ram") = Key[1]: "RAM" = "RAM"
Check returns TO_UPPER("ram") = Key[1]: "RAM" = "RAM"
FeedbackIF Correct = TRUE THENtest TRUE: Feedback calls Praise
test TRUE: Feedback calls Praise
PraiseScore ← Score + 11Score 1Score is BYREF: Praise changes Quiz’s own Score, 0 + 1
Score is BYREF: Praise changes Quiz’s own Score, 0 + 1
PraiseOUTPUT "Correct"CorrectOutput Correct

The whole run

Now all three passes, one row each. Score changes only on a pass where Check returns TRUE.

QNumAnswerCorrectScoreOutputWhat decided it
start0Quiz sets Score ← 0
Quiz sets Score ← 0
QNum 11"ram"TRUE1Question 1CorrectTO_UPPER("ram") = "RAM": TRUE, so Praise adds 1 to Quiz’s Score
TO_UPPER("ram") = "RAM": TRUE, so Praise adds 1 to Quiz’s Score
QNum 22"GPU"FALSEQuestion 2Hint: it executes instructionsTO_UPPER("GPU") ≠ "CPU": FALSE, so ShowHint; Score is unchanged
TO_UPPER("GPU") ≠ "CPU": FALSE, so ShowHint; Score is unchanged
QNum 33"Rom"TRUE2Question 3CorrectTO_UPPER("Rom") = "ROM": TRUE, so Praise adds 1 to Quiz’s Score
TO_UPPER("Rom") = "ROM": TRUE, so Praise adds 1 to Quiz’s Score
Your turn

1 The answers typed are now rom, cpu, RAM. What is Score after each pass?

2 What is output on the last line for these answers?

3 If Praise took Score BYVAL, what would the original run output at the end? Why?

  1. 1
    0, 1, 1: only cpu matches its key (CPU)
  2. 2
    Score: 1
  3. 3
    Score: 0: Praise would add 1 to its own copy, and Quiz’s Score would stay 0
Tick what you can do now
Practise with s26/21 Q8(a), Q8(b), Q8(c); s24/23 Q7(a)(ii); w24/22 Q3(b)
9 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

State-transition diagrams

§12.2 · Program design · state-transition diagrams

Press Start on a microwave and what happens depends on what it was doing already. A state-transition diagram shows the states a system can be in and the events that move it between them. In this microwave, Start begins cooking from Idle but resumes cooking from Paused.

Start at the dot beside Idle and follow the arrows. Each label gives the event first, then after the bar what the microwave does.

IdleCookingPausedSTARTStart pressed | heater onTimer ends | beepDoor opened | heater offStart pressed | heater onStop pressed | clear timer+30 s pressed | add 30 s
IdleCookingPausedSTARTStart pressedheater onTimer endsbeepDoor openedheater offStart pressedheater onStop pressedclear timer+30 s pressedadd 30 sArrow labels: event above, output below.The +30 s loop stays in Cooking.
Sa state the systemcan be inevent | outputa transition: theevent and any outputSTART arrow:the start stateShalting state:a double circle
SA circle represents a state.event | outputA directed transitionSDouble circle: halting state.

Purpose

  • It documents an algorithm whose response to an input depends on its current state.
  • It shows every state, the events (inputs) that cause each transition, and any outputs, so missing or impossible transitions can be found before coding.

States and events

  • A state is a mode or condition the system stays in until something happens: “standby mode”, “cooking”, “alarm sounding”.
  • An event triggers a transition, which may change the state or leave it unchanged. Name the actual event: Start pressed, Door opened or Timer ends.

The same design as a state-transition table

A table holds the same design, one row for each arrow, with each state in the same colour as on the diagram. A question may give either one and ask for the other.

Current stateEvent (input)OutputNext state
IdleStart pressedheater onCooking
Cooking+30 s pressedadd 30 sCooking
CookingDoor openedheater offPaused
Current stateEvent (input)OutputNext state
CookingTimer endsbeepIdle
PausedStart pressedheater onCooking
PausedStop pressedclear timerIdle
Your turn

1 The oven is in Paused. Which event takes it to Idle, and what is output?

2 Which transition leaves the state unchanged?

3 How many arrows does the diagram need to match the table?

  1. 1
    Stop pressed, output: clear timer
  2. 2
    +30 s pressed, a loop on Cooking
  3. 3
    6: one arrow per row
Tick what you can do now
Exam focusEvery arrow needs a direction and a label. From a table, draw one arrow per row, from the current state to the next state, labelled “input | output”. A row whose next state is the current state is a loop on that state.
Practise with s25/22 Q5(a); s26/22 Q1(b)(i), (b)(ii)
10 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Tracing a state-transition diagram

§12.2 · Program design · state-transition diagrams

A state-transition diagram can be run by hand, like a program. Start in the start state and follow one arrow for each input. Each step starts in the state the previous step ended in.

InputsBABAAABOutput so farX1X2X1X3S1S2S3S4STARTABA | X2B | X3B | X1A | X1One input follows one arrow; a loop keeps the same state.
InputsBABAAABOutput so farX1X2X1X3S1S2S3S4STARTAA | X2B | X3BB | X1A | X1A loop keeps the same state.Unlabelled outputs mean none.

Trace the inputs B, A, B, A, A, A, B

One row for each input. Each row starts in the state the row above ended in.

Current stateInputOutputNext stateWhich arrow, and why
input 1S1BX1S1a loop: input B keeps S1; output X1
a loop: input B keeps S1; output X1
input 2S1AnoneS2input A moves S1 to S2; no output
input A moves S1 to S2; no output
input 3S2BnoneS1input B moves S2 to S1; no output
input B moves S2 to S1; no output
input 4S1AnoneS2input A moves S1 to S2; no output
input A moves S1 to S2; no output
input 5S2AX2S3input A moves S2 to S3; output X2
input A moves S2 to S3; output X2
input 6S3AX1S3a loop: input A keeps S3; output X1
a loop: input A keeps S3; output X1
input 7S3BX3S4input B moves S3 to S4; output X3; the halting state, so the trace stops
input B moves S3 to S4; output X3; the halting state, so the trace stops

The diagram answers more than one trace can: count its arrows, find where it halts, or find the shortest route there.

Answers read from the diagram

  • Transitions that lead to a different state: 4.
  • Transitions with an output: 4.
  • Halting state: S4 (double circle).
  • Fewest inputs from S1 to S4: A, A, B.
  • Outputs for input B A B A A A B: X1, X2, X1, X3.
StepCurrent stateInputOutputNext state
1S1BX1S1
2S1AnoneS2
3S2BnoneS1
4S1AnoneS2
5S2AX2S3
6S3AX1S3
7S3BX3S4

Answers read from the diagram

  • Transitions that lead to a different state: 4.
  • Transitions with an output: 4.
  • Halting state: S4 (double circle).
  • Fewest inputs from S1 to S4: A, A, B.
  • Outputs for input B A B A A A B: X1, X2, X1, X3.

The same diagram as a state-transition table: one row for each arrow

Writing the table checks your reading of the diagram: every arrow, loops included, becomes one row.

Current stateInputOutputNext state
S1AnoneS2
S1BX1S1
S2AX2S3
Current stateInputOutputNext state
S2BnoneS1
S3AX1S3
S3BX3S4
Your turn

1 Start in S1 and input A, A, B. List the outputs and the final state.

2 Start in S1 and input B, B, A. Which state does it end in?

3 Which arrows leave S2, and where do they go?

  1. 1
    X2, X3; it ends in S4
  2. 2
    S2: B and B loop on S1 (output X1 each time), then A moves to S2
  3. 3
    input A to S3; input B to S1
Tick what you can do now
Exam focusStart each row in the state the previous row ended in. Write “none” when a transition has no output, and count a loop as a transition that does not change the state.
Practise with s24/22 Q7(b)(i), (b)(ii); w25/21 Q7(a); w25/23 Q7(a)
11 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Syntax, logic and run-time errors

§12.3 · Program testing and maintenance · types of error

Programs go wrong in three different ways, and each shows up at a different time. A syntax error stops the code being translated, a logic error gives the wrong result, and a run-time error stops the program while it runs.

Learn each type with how it is caught: the compiler finds one, testing finds the other two. The last column points to the three listings below.

TypeWhat it isHow it is foundWorked example below
Syntax errorbreaks the rules (grammar) of the languagethe compiler or interpreter reports it; the code cannot be translatedline 5: OUTPT is a misspelt keyword
Logic errorthe algorithm is wrong: it runs but does not give the expected resulttesting: actual and expected results differ; a dry run locates itline 3: > should be >=, so it outputs 2, not 3
Run-time erroran illegal operation while running: it crashes or freezestesting with data that triggers it; prevented by checking values firstline 5: with Count = 0 it divides by zero

Other examples. Syntax: unmatched brackets; NEXT closing a WHILE loop. Logic: a wrong loop count; a wrong starting value; decisions in the wrong order. Run-time: an index out of range; converting a non-numeric string; an endless loop.

TypeWhat it isExamplesHow it is found
Syntax errorA statement does not follow the rules (grammar) of the language.a misspelt keyword; unmatched brackets; NEXT closing a WHILE loopreported by the compiler or interpreter; a program that compiles has none
Logic errorThe algorithm itself is wrong: the program runs but does not give the expected result.a wrong operator; a wrong loop count; a wrong starting value; decisions in the wrong ordertesting: actual and expected results differ; a dry run locates it
Run-time errorWhile running, the program attempts an illegal operation, so it crashes or freezes.dividing by zero; an index out of range; converting a non-numeric string; an endless looptesting with data that triggers it; prevented by checking values first

One example of each

Find the error in each listing before you read the correction below.

Syntax errorline 5
1Total ← 0
2FOR Count ← 1 TO 3
3Total ← Total + Count
4NEXT Count
5OUTPT "Total: ", Total
Logic errorline 3
1Passes ← 0
2FOR Index ← 1 TO 4
3IF Mark[Index] > 50 THEN
4Passes ← Passes + 1
5ENDIF
6NEXT Index
7OUTPUT Passes
Run-time errorline 5
1Sum ← 0
2FOR Index ← 1 TO Count
3Sum ← Sum + Mark[Index]
4NEXT Index
5OUTPUT Sum / Count

What happens, and the correction

Check your answers here: each row says what goes wrong, then the corrected statement and the output it now gives.

ErrorWhat happensCorrectionOutput now
Syntax, line 5OUTPT is not a keyword, so the code cannot be translatedOUTPUT "Total: ", TotalTotal: 6
Logic, line 3marks 50, 72, 38, 61; a pass is 50 or more, but it outputs 2IF Mark[Index] >= 50 THEN3
Run-time, line 5with Count = 0 it divides by zero and stopsIF Count > 0 THEN
   OUTPUT Sum / Count
ELSE
   OUTPUT "No marks"
ENDIF
No marks

Syntax, line 5

OUTPT is not a keyword: the listing cannot be translated.

Corrected statement
OUTPUT "Total: ", Total

Output: Total: 6

Logic, line 3

A pass is 50 or more. For 50, 72, 38, 61, the original test outputs 2.

Corrected statement
IF Mark[Index] >= 50 THEN

Output now: 3

Run-time, line 5

Count = 0 would divide by zero. Test Count before calculating the mean.

Correction
IF Count > 0 THEN
OUTPUT Sum / Count
ELSE
OUTPUT "No marks"
ENDIF

Output for Count = 0: No marks

Your turn

1 A program outputs 9 when the expected result is 10. Which type of error is this most likely to be?

2 IF Score > 10 THEN is typed as IF Score > 10 THN. Which type of error?

3 A program stops when it reads Item[11] from an array declared [1:10]. Which type of error?

  1. 1
    logic: it runs but does not give the expected result
  2. 2
    syntax: THN is not a keyword
  3. 3
    run-time: the index is out of range
Tick what you can do now
Exam focusName the type and describe it: syntax — the rules (grammar) of the language are not followed; logic — it runs but does not behave as expected; run-time — it performs an illegal operation, such as dividing by zero.
Practise with s25/21 Q2(c); s24/22 Q5(b); w24/21 Q4(a); w24/22 Q5(a), (b); s25/22 Q2(b)(iii)
12 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Locate, identify and correct errors

§12.3 · Program testing and maintenance · correcting errors

This function looks finished, but it crashes, and its count is wrong too. InRange() should count the temperatures in the global array Temps[1:5] from Low to High inclusive.

Pseudocodecontains three errors
 1FUNCTION InRange(Low : INTEGER, High : INTEGER) RETURNS INTEGER
 2DECLARE Day, Count : INTEGER
 3Count ← 1
 4FOR Day ← 1 TO 6
 5IF Temps[Day] > Low AND Temps[Day] <= High THEN
 6Count ← Count + 1
 7ENDIF
 8NEXT Day
 9RETURN Count
10ENDFUNCTION

Test run

Temps holds 15, 22, 18, 9, 15 (Temps[1:5]). InRange(15, 21) should return 3.

Actual: a run-time error at line 5 when Day = 6: Temps[6] is outside the array.

Dry run after correcting line 4

A dry run compares what each line does with what it should do. The row where they differ points to the faulty line.

Day 1, statement by statement
LineStatement that runsDayCountWritesWhat happens
4FOR Day ← 1 TO 51Day 1line 4 corrected: the loop now stops at the last index, 5
line 4 corrected: the loop now stops at the last index, 5
5IF Temps[Day] > Low AND Temps[Day] <= High THENtest Temps[1] = 15; 15 > 15 is FALSE, so line 6 is skipped
test Temps[1] = 15; 15 > 15 is FALSE, so line 6 is skipped
8NEXT Daytest Count is still 1, but 15 should have been counted
test Count is still 1, but 15 should have been counted

Now the whole run, one row per day. Wherever the Line 5 test and Should be columns disagree, line 5 is at fault.

DayTemps[Day]Line 5 testShould beCountWhat happens
start1line 3 sets Count ← 1: already one too many
line 3 sets Count ← 1: already one too many
Day 1115FALSETRUE15 > 15 is FALSE, but 15 is from 15 to 21, so it should be counted: the line 5 error
15 > 15 is FALSE, but 15 is from 15 to 21, so it should be counted: the line 5 error
Day 2222FALSEFALSE22 is outside 15 to 21: correctly not counted
22 is outside 15 to 21: correctly not counted
Day 3318TRUETRUE218 is in range: Count ← Count + 1
18 is in range: Count ← Count + 1
Day 449FALSEFALSE9 is outside 15 to 21: correctly not counted
9 is outside 15 to 21: correctly not counted
Day 5515FALSETRUE15 > 15 is FALSE, but 15 is from 15 to 21, so it should be counted: the line 5 error
15 > 15 is FALSE, but 15 is from 15 to 21, so it should be counted: the line 5 error
end2RETURN 2, but 3 temperatures are in range
RETURN 2, but 3 temperatures are in range

A dry run is not the only way in. When the fault is harder to find by hand, these help:

Ways to expose a fault

  • a dry run: a trace table with test data
  • extra OUTPUT statements; different test values to see which fail
  • an IDE: set a breakpoint in InRange to pause at a chosen statement; then single-step one statement at a time while a watch window displays the changing Day and Count values
DayTemps[Day]Line 5 testShould beCount
1
115FALSETRUE
222FALSEFALSE
318TRUETRUE2
49FALSEFALSE
515FALSETRUE

Ways to expose a fault

  • a dry run: a trace table with test data
  • extra OUTPUT statements; different test values to see which fail
  • an IDE: set a breakpoint in InRange to pause at a chosen statement; then single-step one statement at a time while a watch window displays the changing Day and Count values

Identify and correct

The run exposed three faults. For each one, give the line number, the type of error and the corrected line written in full.

LineErrorTypeCorrected line
3Count starts at 1, so the result is one too manylogicCount ← 0
4the loop runs to 6, but the array ends at index 5run-timeFOR Day ← 1 TO 5
5> leaves out a temperature equal to LowlogicIF Temps[Day] >= Low AND Temps[Day] <= High THEN

Correct line 3 · logic

Count starts at 1, so the result is one too many

Corrected statement
Count ← 0

Correct line 4 · run-time

the loop runs to 6, but the array ends at index 5

Corrected statement
FOR Day ← 1 TO 5

Correct line 5 · logic

> leaves out a temperature equal to Low

Corrected statement
IF Temps[Day] >= Low AND Temps[Day] <= High THEN
Your turn

1 With only line 4 corrected, what does InRange(15, 21) return?

2 Which corrected line makes a temperature equal to Low count?

3 With all three lines corrected, Temps holds 21, 15, 30, 16, 14. What does InRange(15, 21) return?

  1. 1
    2
  2. 2
    line 5: >= instead of >
  3. 3
    3: 21, 15, 16 are from 15 to 21
Tick what you can do now
Exam focusGive the line number and the corrected statement in full: “line 5: IF Temps[Day] >= Low AND …”. Then retest with the data that failed, and with data near each boundary.
Practise with s24/22 Q5(a)(i); w24/22 Q5(a); w24/22 Q1(b)
13 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Dry run, walkthrough, white-box and black-box

§12.3 · Program testing and maintenance · testing methods

No program can be tried with every possible input, so testers must choose their data with care. Testing methods differ in how the test data is chosen: from the code (white-box) or from the specification (black-box). A dry run and a walkthrough work through the code by hand.

Two of these methods are ways of checking code by hand; the other two say where the test data comes from.

MethodWhat it is
Dry runWorking through the code by hand with test data, recording each variable and output in a trace table.
WalkthroughGoing through the program a line at a time, often with others, with test data and expected outputs: an unexpected value or path shows an error.
White-boxTest data is chosen from the code, so that every path through the program is tested.
Black-boxTest data is chosen from the specification, without looking at the code; actual results are compared with expected results. A difference exposes a logic or run-time error.

White-box: exercise the four coded paths

Each decision has a TRUE and a FALSE branch. Choose data so that every branch is taken.

Pseudocode
 1FUNCTION Charge(Kg : REAL,
 2Express : BOOLEAN) RETURNS INTEGER
 3DECLARE Cost : INTEGER
 4IF Kg <= 2.0 THEN
 5Cost ← 5
 6ELSE
 7Cost ← 8
 8ENDIF
 9IF Express = TRUE THEN
10Cost ← Cost * 2
11ENDIF
12RETURN Cost
13ENDFUNCTION

Specification

A parcel of up to and including 2 kg costs $5; a heavier parcel costs $8. Express delivery doubles the cost. A weight of 0 kg or less is invalid: return −1.

Each diamond is one IF in the code. Its labels name the tests that take each branch, and the table gives their data.

Kg <= 2.0line 4Cost ← 5Cost ← 8TRUE: tests 1, 2FALSE: tests 3, 4Express = TRUEline 9Cost ← Cost * 2Cost unchangedTRUE: tests 2, 4FALSE: tests 1, 3
Kg <= 2.0line 4Cost ← 5Cost ← 8TRUEtests 1, 2FALSEtests 3, 4Express = TRUEline 9Cost ← Cost * 2Cost unchangedTRUEtests 2, 4FALSEtests 1, 3
TestMethodKg, ExpressPurposeExpectedActual
1white-box1.5, FALSEline 4 TRUE, line 9 FALSE55
2white-box1.5, TRUEline 4 TRUE, line 9 TRUE1010
3white-box3.0, FALSEline 4 FALSE, line 9 FALSE88
4white-box3.0, TRUEline 4 FALSE, line 9 TRUE1616

Test 1: white-box

Kg, Express: 1.5, FALSE

line 4 TRUE, line 9 FALSE

ExpectedActual
55

Test 2: white-box

Kg, Express: 1.5, TRUE

line 4 TRUE, line 9 TRUE

ExpectedActual
1010

Test 3: white-box

Kg, Express: 3.0, FALSE

line 4 FALSE, line 9 FALSE

ExpectedActual
88

Test 4: white-box

Kg, Express: 3.0, TRUE

line 4 FALSE, line 9 TRUE

ExpectedActual
1616
Your turn

1 Give white-box test data that makes line 4 FALSE and line 9 TRUE, with the expected result.

2 A tester picks 2.0 kg because the specification says “up to and including 2 kg”, without reading the code. Which method is that?

3 Which method goes through the program a line at a time, often with other people?

  1. 1
    for example Kg = 3.0, Express = TRUE: expected 16
  2. 2
    black-box: the data comes from the specification
  3. 3
    a walkthrough
Tick what you can do now
Exam focusChoose data that makes the decisions take different paths, and give the expected result for each test. Here the four Kg/Express combinations reach all four coded paths.
Practise with s25/22 Q2(b)(i); w25/21 Q1(b); s25/23 Q4(b)
14 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Black-box tests from the specification

§12.3 · Program testing and maintenance · specification and implementation

The four white-box tests passed, yet the code is still wrong: it never checks for an invalid weight. Black-box tests come from the specification, so they can find a rule the code left out.

A black-box tester sees only the specification, never the code:

Specification

A parcel of up to and including 2 kg costs $5; a heavier parcel costs $8. Express delivery doubles the cost. A weight of 0 kg or less is invalid: return −1.

Black-box tests on the original code

Compare each expected result, from the specification, with what the original code returns.

TestMethodKg, ExpressPurposeExpectedOriginal actual
5black-box2.0, FALSEboundary: the heaviest $5 parcel55
6black-box2.1, FALSEboundary: just over 2 kg88
7black-box-1.0, FALSEabnormal: an invalid weight-15

Test 5: black-box

Kg, Express: 2.0, FALSE

boundary: the heaviest $5 parcel

ExpectedOriginal actual
55

Test 6: black-box

Kg, Express: 2.1, FALSE

boundary: just over 2 kg

ExpectedOriginal actual
88

Test 7: black-box

Kg, Express: -1.0, FALSE

abnormal: an invalid weight

ExpectedOriginal actual
-15

Test 7 fails, and the failure names the missing rule. The repair adds that check before anything else.

Repair: check the invalid weight first
FUNCTION Charge(Kg : REAL,
Express : BOOLEAN) RETURNS INTEGER
DECLARE Cost : INTEGER
IF Kg <= 0 THEN
RETURN -1
ENDIF
IF Kg <= 2.0 THEN
Cost ← 5
ELSE
Cost ← 8
ENDIF
IF Express = TRUE THEN
Cost ← Cost * 2
ENDIF
RETURN Cost
ENDFUNCTION

Why the invalid case failed

  • The specification says a weight of 0 kg or less returns −1.
  • In the original code, −1.0 passes Kg <= 2.0, so it returns 5.
  • The repair checks Kg <= 0 first and returns −1. Every positive weight still gives its old result.
Your turn

1 Give a black-box test that uses 0 kg. What is the expected result, and what did the original code return?

2 What does the repaired function return for Charge(0.5, TRUE)?

3 Why did white-box tests 1 to 4 not find this fault?

  1. 1
    Charge(0, FALSE): expected -1; the original returned 5
  2. 2
    10
  3. 3
    they were chosen from the code’s paths, and the code has no path for an invalid weight
Tick what you can do now
Practise with s25/22 Q2(b)(iii)
15 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Testing stages: stub to acceptance

§12.3 · Program testing and maintenance · stub, integration, alpha, beta and acceptance testing

A fault is easiest to find in a small piece of code, so testing starts small and widens. It happens in stages: each module on its own, then modules together, then in-house testers, users and finally the customer.

Unit (module) testingeach module as coded;stubs fill the gapsIntegrationtested modules arecombined and retestedAlphain-house testing bydevelopers or testersBetaa few potential users,in their real settingAcceptancethe customer checksrequirements are metin-house: the developeroutside: users and the customer
In-house: developers and testersUnit: one module, with stubs if neededIntegration: modules work togetherAlpha: internal testing before releaseOutside: users and customerBeta: selected potential usersAcceptance: customer requirementsActivities can overlap; this is not a strict sequence.

Who tests, when, and why

Each stage has its own testers and its own purpose: who tests, when, and what it checks.

MethodWho and whenPurpose
Stub testingwhile modules are being written, or when one does not workA simple (dummy) module replaces the missing module. It returns a known value or outputs a message to show it has been called, so the calling code can be tested.
Integrationwhen modules that have been tested on their own are combinedTests that the modules work together: parameters and return values pass correctly. Modules are often added one at a time.
Alphain-house, by developers or dedicated testers, as modules are coded and before releaseFinds errors before anyone outside the developer uses it.
Betaa small group of potential users, in the real world, before general releaseUsers check it works as required and report problems and suggestions, which can be addressed before general release.
Acceptancethe customer, at hand-overChecks the software meets the agreed requirements, so the customer can approve (sign off) it.

A stub in action

A module can be tested before the modules it calls are written, with a stub in their place.

Pseudocodestub testing
// a stub: Discount() is not written yet
FUNCTION Discount(Code : STRING) RETURNS REAL
OUTPUT "Discount called with ", Code
RETURN 5.0
ENDFUNCTION

// the calling code being tested
Price ← 40.0
Price ← Price - Discount("SPRING")
OUTPUT "To pay: ", Price

Output

Discount called with SPRING
To pay: 35.0

The message proves the call was made; the fixed return value lets the calculation be checked by hand: 40.0 − 5.0 = 35.0.

Your turn

1 Module Total is finished, but the Discount module it calls has not been written. How can Total be tested now?

2 Who carries out beta testing, and where?

3 What does acceptance testing check?

  1. 1
    stub testing: a simple dummy Discount returns a known value or outputs a message, so Total can be run and checked
  2. 2
    a small group of potential users, in their real setting, before general release
  3. 3
    that the software meets the agreed requirements, so the customer can sign it off
Tick what you can do now
Exam focusStub testing: a simple (dummy) module replaces the unfinished module and returns an expected value or outputs a message to show it was called. The order is not strict: alpha testing can overlap module testing in-house; integration checks the interfaces when tested modules are combined.
Practise with w24/23 Q5(b); s26/22 Q1(f)(i), (f)(ii); w24/21 Q5(b)(ii); w25/22 Q5(b); s26/23 Q3(a)
16 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Test strategy, test plan and test data

§12.3 · Program testing and maintenance · test plans

Testing without a plan tends to try the easy cases and miss the edges. A test plan lists each test with its data, the type of test data and the expected outcome, worked out before the program is run.

Two documents, decided at different times: the strategy first, at the design stage, then the plan that carries it out.

Test strategy

Decided at the design stage. It sets the approach: which testing methods are used and when, who tests, and what is tested: flow of control, validation, files. Representative inputs are chosen when exhaustive testing is impractical.

Test plan

The detailed list of tests: each test’s number, purpose, test data and its type, and expected outcome (worked out before testing). The actual outcome is recorded when the test is run.

Types of test data

Most faults hide at the limits, which is why the type of each test value matters. Each type keeps one colour in every table and example.

Type of test dataMeaningOutcome
Normaltypical valid data, well inside the rangeaccepted
Abnormal (erroneous)data that should be rejected: out of range, or the wrong typerejected
Extremethe largest and the smallest values that are still validaccepted
Boundaryeach side of a limit: the last valid and the first invalid valueaccepted / rejected
Type of test dataMeaningOutcome
Normaltypical valid data, well inside the rangeaccepted
Abnormal (erroneous)data that should be rejected: out of range, or the wrong typerejected
Extremethe largest and the smallest values that are still validaccepted
Boundaryeach side of a limit: the last valid and the first invalid valueaccepted / rejected

A test plan: integer ages 11–17, inclusive

Put the valid range on a number line first: the test values sit at its edges and just outside them. Each coloured value then becomes one row of the plan.

accepted: 11 to 17rejectedrejected91011extreme121314normal151617extreme1819boundary 10 | 11boundary 17 | 18abnormal, off the line−3a negative age
91011extreme121314normal151617extreme1819boundary10 | 11boundary17 | 18accepted11 to 17rejectedrejectedabnormal, off the line−3a negative age
valid: 11 to 17 inclusive789101112131415161718192021-3 ◀accepted (TRUE)rejected (FALSE)
Valid integer ages: 11–17, inclusive10111213141516171811, 14, 17: accepted10, 18 and −3: rejectedTest each limit and both adjacent sides.
TestDataTypePurposeExpected
114normala typical valid ageTRUE
211extreme / boundarythe lowest valid ageTRUE
317extreme / boundarythe highest valid ageTRUE
410boundary (abnormal)just below the rangeFALSE
518boundary (abnormal)just above the rangeFALSE
6-3abnormala negative ageFALSE
TestDataTypePurposeExpected
114normala typical valid ageTRUE
211extreme / boundarythe lowest valid ageTRUE
317extreme / boundarythe highest valid ageTRUE
410boundary (abnormal)just below the rangeFALSE
518boundary (abnormal)just above the rangeFALSE
6-3abnormala negative ageFALSE
Test both sides: 10/11/12 and 16/17/18. Here the extreme valid ages are 11 and 17; 10 and 18 are invalid boundary data. A negative test is useful only if the stated input source can produce one.
Your turn

1 A month number must be a whole number from 1 to 12. Give the two extreme values.

2 Give the two boundary pairs, with the expected outcome of each value.

3 Give one abnormal value of the wrong type.

  1. 1
    1 and 12, both accepted
  2. 2
    0 rejected | 1 accepted; 12 accepted | 13 rejected
  3. 3
    for example “May” or 3.5
Tick what you can do now
Exam focusGive exact test data and the expected outcome; include its type when requested. Test both sides of each limit: the extreme valid value (accepted) and the value just outside it (rejected). “A very large number” is not test data.
Practise with w24/21 Q5(b)(i); s25/21 Q6(a); s26/23 Q3(c)
17 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Choosing test data for a test plan

§12.3 · Program testing and maintenance · test data

A test is useful only when its result points to one cause. Good test data checks one thing at a time: each invalid test breaks one rule, and a loop is tested with no data, one item and many items.

Several rules: break one rule per test

A username must have (1) 6 to 10 characters, (2) a letter first and (3) no spaces. If a test broke two rules, a rejection would not show which check works.

Test data(1) 6 to 10 characters(2) letter first(3) no spacesExpected
"Rowan7"✓✓✓accepted
"Row7"✗ broken✓✓rejected
"Rowan202512"✗ broken✓✓rejected
"7Rowan"✓✗ broken✓rejected
"Ro wan7"✓✓✗ brokenrejected
Test dataRule brokenReason
"Rowan7"nonevalid: all three rules met
"Row7"rule 1too short
"Rowan202512"rule 1too long
"7Rowan"rule 2starts with a digit
"Ro wan7"rule 3contains a space

A sequence ended by a terminator

CountHigh() counts the values above 50 and the values of 50 or less; 0 ends the input and is not counted.

Read the plan beside the loop: it runs CountHigh with several values, with one, and with none, and puts 50 and 51 either side of the limit.

Pseudocode
PROCEDURE CountHigh()
DECLARE Value, High, Low : INTEGER
High ← 0
Low ← 0
INPUT Value
WHILE Value <> 0
IF Value > 50 THEN
High ← High + 1
ELSE
Low ← Low + 1
ENDIF
INPUT Value
ENDWHILE
OUTPUT High, " high, ", Low, " low"
ENDPROCEDURE

CALL CountHigh()
Input sequencePurposeExpected output
72, 15, 50, 51, 0a mix, including 50 and 51 either side of the boundary2 high, 2 low
60, 99, 0only high values2 high, 0 low
5, 50, 0only low values0 high, 2 low
51, 0one high value, then the terminator1 high, 0 low
0no values: the terminator on its own0 high, 0 low

Inputs: 72, 15, 50, 51, 0

a mix, including 50 and 51 either side of the boundary

Expected: 2 high, 2 low

Inputs: 60, 99, 0

only high values

Expected: 2 high, 0 low

Inputs: 5, 50, 0

only low values

Expected: 0 high, 2 low

Inputs: 51, 0

one high value, then the terminator

Expected: 1 high, 0 low

Inputs: 0

no values: the terminator on its own

Expected: 0 high, 0 low

Choosing test data: a checklist

  • normal data, both sides of every limit, and abnormal data of each kind
  • one rule broken in each invalid test
  • data covering each decision outcome or required result class, and different executable paths
  • for loops and sequences: no data, one item and many items
Your turn

1 Which of these usernames breaks only rule 3: "Sam Lee1", "Sa m", "SamLee1"?

2 What does CountHigh output for the inputs 50, 51, 0?

3 Why test CountHigh with 0 on its own?

  1. 1
    "Sam Lee1": it has 8 characters and starts with a letter, but has a space
  2. 2
    1 high, 1 low
  3. 3
    the loop body never runs, so it checks the output for no data: 0 high, 0 low
Tick what you can do now
Exam focusMake each invalid test break one rule only, while meeting all the others, so a rejection has a single cause. Give a purpose for each test that is different from the others.
Practise with s26/22 Q1(c)
18 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Testing every possible return value

§12.3 · Program testing and maintenance

A result that no test ever produces is a result nobody has checked. When a function can return only a few values, plan one test for each possible result, and work out each expected result before you run it.

NextGroup uses (N MOD 3) + 1 to cycle between three group codes. Its contract accepts only INTEGER inputs 1, 2 or 3. The tests use only those valid inputs and check every group it can return.

The function under test
FUNCTION NextGroup(
N : INTEGER) RETURNS INTEGER
RETURN (N MOD 3) + 1
ENDFUNCTION

Derive the complete result range

1
For inputs 1, 2, 3, the remainders after division by 3 are 1, 2, 0.
2
Adding 1 gives results 2, 3, 1: the complete return set is {1, 2, 3}.
3
Choose valid inputs that collectively reach all three results.

One planned test per possible result

Three inputs, three different results: together these tests reach every value the function can return.

Input NN MOD 3Return112MOD 3+ 1223MOD 3+ 1301MOD 3+ 1every group once

Written as a test plan, each row gives an input and the return worked out before the call is run.

Input NN MOD 3Expected return
112
223
301

After running each call, record its actual return and compare it with the expected value. A wrong result identifies a failed test; merely reaching a result is not enough.

Repeating one test does not cover every result

  • Calling NextGroup(2) three times should return 3 each time.
  • Those calls test result 3 again and again; they give no evidence for results 1 and 2.
  • The three different inputs above cover the full result set.
Your turn

1 A function returns (N MOD 2) + 1 for valid inputs 1 to 4. List every result it can return.

2 Give the fewest inputs that test every result, with the expected return for each.

3 NextGroup(3) is called twice. Which results have been tested?

  1. 1
    1, 2
  2. 2
    two inputs, for example 1 (returns 2) and 2 (returns 1)
  3. 3
    only result 1
Tick what you can do now
Practise with w25/23 Q6(a)
19 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Maintenance and avoiding faults

§12.3 · Program testing and maintenance · maintenance

A program in use still needs work. Some errors only appear with rare data, and the requirements, hardware and laws around a program change. Software does not wear out: maintenance means changing the code.

Three types of maintenance

The reason for a change decides its type: a fault to correct, a change around the program, or an improvement.

TypeWhen it is neededWorked example: a school library app
Correctivethe program does not work as expected: a bug (a logic or run-time error) found after the program is in useA fine is charged when a book is returned on its due date. The comparison is corrected.
Adaptivethe requirements change, new technology or hardware is used, library modules change, or legislation changesThe school moves to tablets and a new law limits what pupil data may be kept. The app is changed for both.
Perfectivethe program works, but its performance or maintainability is improvedSearching the catalogue is slow: a faster search is written and repeated code is moved into a module.
TypeWhen it is neededExample
Correctivethe program does not work as expected: a bug (a logic or run-time error) is found after the program is in usea total is wrong when a list is empty; a password is shown instead of hidden
Adaptivethe requirements change, new technology or hardware is used, library modules change, or legislation changesrunning on new hardware; a new tax rule; extra features users ask for
Perfectivethe program works, but its performance or maintainability is improveda faster search; repeated code moved into a module; clearer identifiers

Two questions decide the type

Ask the top question first, and the second only if the program works. The box you reach is the type.

Does it work as expected?noyesCorrectiveHas something around it changed?(requirements, hardware, the law)yesnoAdaptivePerfectiveit is improved

Every corrective change is a fault that slipped through. These habits, used while the program is written, mean fewer of them.

Avoiding faults in the first place

  • a clear requirements specification, so the right problem is solved
  • meaningful identifiers, so the code is easier to understand, debug, test and maintain
  • comments, indentation, white space and keywords in capitals
  • modules with local variables and parameters
  • constants for fixed values: entered once, changed in one place
  • tried and tested library routines
  • validating input and checking values before an operation

Classify the change

ChangeType
Bugs are reported in the first week of usecorrective
The program is changed to work with new hardwareadaptive
The code is changed to improve the speed of responseperfective
Staff need features that were not originally agreedadaptive
A new law changes how customer data must be storedadaptive
Comments and meaningful names are added for future editorsperfective

Avoiding faults in the first place

  • a clear requirements specification, so the right problem is solved
  • meaningful identifiers, so the code is easier to understand, debug, test and maintain
  • comments, indentation, white space and keywords in capitals
  • modules with local variables and parameters
  • constants for fixed values: entered once, changed in one place
  • tried and tested library routines
  • validating input and checking values before an operation
Your turn

Which type of maintenance is each change? Use the two questions.

1 Bugs are reported in the first week of use.

2 The program is changed to work with new hardware.

3 The code is changed to improve the speed of response.

4 Staff need features that were not originally agreed.

5 A new law changes how customer data must be stored.

6 Comments and meaningful names are added for future editors.

  1. 1
    corrective
  2. 2
    adaptive
  3. 3
    perfective
  4. 4
    adaptive
  5. 5
    adaptive
  6. 6
    perfective
Tick what you can do now
Exam focusGive the type with a matching reason: adaptive — a change in requirements, technology or legislation; corrective — the program does not work as expected; perfective — the program works but is improved, for example made faster.
Practise with s25/22 Q1(b)(i), (b)(ii); s26/23 Q3(a); s26/21 Q3(b)
20 / 21
9618 · Unit 12 · Software development
Revisionbyexamplicity

Analyse and amend an existing program

§12.3 · Program testing and maintenance · amending a program

Changing one line of a working program can quietly break another. To amend a program, analyse it first: trace it, and find every line that depends on the part being changed.

To amend a program, analyse it first: trace it, and find every line that depends on the part being changed.

Two new requirements: process 1 to 7 days, and also output the day of the highest temperature. Temps[1:7] holds 18, 21, 24, 19, 17, 22, 19. NumDays must be at least 1 and no greater than the seven stored values.

Existing
 1PROCEDURE Summary()
 2DECLARE Day, Total, Max : INTEGER
 3Total ← 0
 4Max ← Temps[1]
 5FOR Day ← 1 TO 7
 6Total ← Total + Temps[Day]
 7IF Temps[Day] > Max THEN
 8Max ← Temps[Day]
 9ENDIF
10NEXT Day
11OUTPUT "Mean: ", Total / 7
12OUTPUT "Highest: ", Max
13ENDPROCEDURE
14
15CALL Summary()

Output: Mean: 20.0 · Highest: 24

Amended
 1PROCEDURE Summary(NumDays : INTEGER)
 2DECLARE Day, Total, Max, MaxDay : INTEGER
 3Total ← 0
 4Max ← Temps[1]
 5MaxDay ← 1
 6FOR Day ← 1 TO NumDays
 7Total ← Total + Temps[Day]
 8IF Temps[Day] > Max THEN
 9Max ← Temps[Day]
10MaxDay ← Day
11ENDIF
12NEXT Day
13OUTPUT "Mean: ", Total / NumDays
14OUTPUT "Highest: ", Max, " on day ", MaxDay
15ENDPROCEDURE
16
17CALL Summary(5)

Output: Mean: 19.8 · Highest: 24 on day 3

The amendments

Each change, where it goes and why. Write each new line in full, and say where it goes.

Line (new)ChangeWhy
1add the parameter NumDays : INTEGERthe number of days now varies
2declare MaxDaya new value to output
5insert MaxDay ← 1day 1 is the highest so far
6, 13replace the literal 7 with NumDaysloop and divide for the given number of days
10insert MaxDay ← Dayrecord the day of each new highest value
14output MaxDay as wellthe new requirement
17call Summary(5)supply the required day count in the caller
Replacing the literal 7 with a parameter also makes the program easier to maintain: the value is now set in one place, by the caller. The strict > comparison keeps the first day when the highest value is tied.
Your turn

1 What does the amended program output for CALL Summary(3)?

2 Why is MaxDay set to 1 before the loop?

3 After the change, which old test should be run again, and what must it output?

  1. 1
    Mean: 21.0 then Highest: 24 on day 3
  2. 2
    Max starts as Temps[1], so day 1 is the highest so far until a larger value is found
  3. 3
    the old seven-day run, Summary(7): it must still output Mean: 20.0 and Highest: 24, now followed by on day 3
Tick what you can do now
Exam focusWrite each new or changed line in full and say exactly where it goes: “insert MaxDay ← Day after line 8 of the existing code”. Keep the parts that already work, and retest with the old test data as well as new data.
Practise with s24/21 Q5(b)(i), (b)(ii); s22/22 Q4(b) (older paper: count parameter amendment)
21 / 21