Understand how to create a maintainable program

Programming – Creating a Maintainable Program (Cambridge IGCSE 0478)

Maintainability is the ease with which a program can be understood, modified and extended over time. In the Cambridge IGCSE 0478 syllabus a maintainable program is required for:

  • AO1 – Knowledge and understanding of programming concepts.
  • AO2 – Analyse a problem, design a solution and produce pseudocode/flowcharts.
  • AO3 – Evaluate design choices and justify why they improve maintainability.

1. Background – Core Computing Concepts (Syllabus Topics 1‑6)

1.1 Data Representation

  • Numbers are stored in binary (base‑2). Example: decimal 25 → 11001₂.
  • Hexadecimal (base‑16) provides a compact way to view binary groups of four bits. Example: 11001₂ = 19₁₆.
  • Two’s‑complement is used for signed integers. To obtain –25: invert 0001 10011110 0110, add 1 → 1110 0111₂.
  • Characters are encoded as ASCII (7‑bit) or Unicode (UTF‑8/16). Example: ‘A’ = 65₁₀ = 0100 0001₂.
  • Images, sound and other media are stored as sequences of bytes; compression (e.g., JPEG, MP3) reduces the amount of data that must be processed.

1.2 Data Transmission & Error Detection

  • Data are sent in packets over wired (USB, Ethernet) or wireless (Wi‑Fi, Bluetooth) links.
  • Transmission can be packet‑switched (Internet) or circuit‑switched (telephone).
  • Simple error‑detection method: parity bit. Even parity adds a 0 or 1 so the total number of 1‑bits is even; the receiver checks the parity to spot single‑bit errors.

1.3 Computer Hardware (CPU, Memory, Execution Cycle)

  • The CPU contains registers, an arithmetic‑logic unit (ALU) and a control unit.
  • Typical execution model: Fetch – Decode – Execute (FDE) cycle.
  • Modern CPUs have multiple cores, cache memory, and may be embedded in devices (e.g., smartphones).
  • Understanding the hardware helps you choose appropriate data types (e.g., int vs float) and write efficient, maintainable code.

1.4 Software Layers

  • System software (operating system, device drivers) manages hardware resources and handles interrupts.
  • Application software runs on top of the OS and performs the tasks you program.
  • Integrated Development Environments (IDEs) combine editors, debuggers and compilers/interpreters, making it easier to write maintainable code.

1.5 The Internet, URLs, HTTP/HTTPS & Cyber‑Security

  • Web resources are addressed by URLs (e.g., https://www.example.com/index.html).
  • Communication uses the HTTP protocol; HTTPS adds encryption (TLS) for security.
  • Cookies store small pieces of data on the client side; they must be validated to avoid security risks.
  • Input validation (covered later) is the first line of defence against common attacks such as injection.

1.6 Automated & Emerging Technologies

  • Sensors and actuators generate real‑time data that must be read, validated and stored.
  • Robotics and AI systems rely on modular code so that algorithms can be swapped or updated without rewriting the whole program.
  • Example: a temperature‑sensor logger that records readings, checks they are within plausible limits, and writes them to a file – all tasks are best split into separate functions for maintainability.

2. Syllabus‑required Pseudocode Conventions (AO1)


3. Key Principles of a Maintainable Program (AO2 + AO3)

  • Readability – clear layout, consistent formatting, meaningful names.
  • Modularity – break the solution into independent, reusable components (functions / procedures).
  • Documentation – comments, header blocks and doc‑strings that explain why the code does something.
  • Validation & Verification – checks that input data are correct (validation) and that the program produces the expected result (verification).
  • Testing & Debugging – systematic unit and integration tests plus debugging strategies.
  • Evaluation (AO3) – justify design decisions and reflect on their impact on maintainability.

4. Writing Readable Code

  1. Consistent 4‑space indentation.
  2. Descriptive identifiers (see the naming table below).
  3. Logical grouping of related statements – separate sections with a blank line.
  4. Use of whitespace around operators and after commas.

4.1 Naming Conventions

Element Recommended Style Example
Variables snake_case (Python) / lowerCamelCase (Java) / PascalCase (pseudocode) total_score, studentName, ScoreTotal
Constants UPPER_SNAKE_CASE MAX_ATTEMPTS, TAX_RATE
Functions / Procedures snake_case (Python) / lowerCamelCase (Java) / PascalCase (pseudocode) calculate_average, computeTotal, CalculateTotal
Classes (if used) UpperCamelCase StudentRecord
AO3 Evaluation Box – Naming
When you decide to use snake_case for variables, explain why it improves readability for a future maintainer (e.g., it separates words clearly, matches the language’s standard library, and avoids ambiguity with class names).

5. Using Comments Effectively (AO1 + AO3)

  • Header comment at the top of each file:
    # Author:  Jane Doe
    # Date:    30‑12‑2025
    # Purpose: Calculate and print a sales receipt
    # Version: 1.0
            
  • Inline comments for non‑obvious logic (placed on a separate line or after the statement, preceded by # or //).
  • Doc‑strings / procedure comments describing parameters, return values and side effects:
    def calculate_total(price, quantity):
        """
        Returns the total cost for a line item.
        Parameters:
            price    – unit price (float)
            quantity – number of units (int)
        Returns:
            float – price × quantity
        """
            

6. Modular Design with Functions (AO2)

Each function should perform a single, well‑defined task. This makes the code easier to test, reuse and modify.

FUNCTION CalculateTotal(price, quantity)
    RETURN price * quantity
END FUNCTION

PROCEDURE PrintReceipt(items)
    total ← 0
    FOR EACH item IN items
        lineTotal ← CalculateTotal(item.price, item.qty)
        total ← total + lineTotal
        // display line (item name, qty, lineTotal)
    END FOR
    // display total
END PROCEDURE

7. Validation & Verification (AO2)

Validation checks that input data meet required criteria before they are processed. Verification checks that the program’s output matches the expected result.

  • Range check – e.g. a score must be between 0 and 100.
  • Type check – ensure a value is numeric before arithmetic.
  • Format check – e.g. a date entered as DD/MM/YYYY.

Example validation block (pseudocode)

READ score
IF score < 0 OR score > 100 THEN
    DISPLAY "Error: score must be between 0 and 100"
    STOP
END IF

Verification example – unit test

# Test CalculateTotal
INPUT price = 9.99, quantity = 3
EXPECTED output = 29.97
ACTUAL = CalculateTotal(price, quantity)
ASSERT ACTUAL = EXPECTED

8. Testing Strategies (AO2)

8.1 Unit Testing

Test each function in isolation with known inputs and expected outputs.

# Unit test for CalculateAverage
INPUT scores = [80, 90, 70]
EXPECTED = 80.0
ACTUAL = CalculateAverage(scores)
ASSERT ACTUAL = EXPECTED

8.2 Integration Testing

Combine functions and verify that data flow works correctly.

# Integration test for PrintReceipt
CALL PrintReceipt([ {price:5, qty:2}, {price:7.5, qty:1} ])
# Verify that the displayed total equals 17.5

8.3 Trace Tables (required for the exam)

A trace table records the values of variables after each step of execution.

Step price quantity total
Initial0
CALL CalculateTotal(5,2)5210
CALL CalculateTotal(7.5,1)7.5117.5

9. Debugging Techniques (AO3)

  • Print‑statement debugging – temporarily output variable values.
  • Step‑through debugging – use the IDE’s debugger to execute line‑by‑line and watch variables.
  • Rubber‑duck debugging – explain the code aloud (or to a peer) to uncover logical errors.

10. Evaluation of Design Choices (AO3)

Justifying a design decision
*When you place input validation at the start of a procedure, explain how this prevents downstream errors, reduces the need for additional checks later, and therefore makes the program easier to maintain.*

11. Optional Enrichment – Version Control (AO3)

Version control is not examined but helps students experience real‑world software development.

git init
git add receipt.py
git commit -m "Add CalculateTotal function"
git branch feature/validation

12. Worked Example – From Requirement to Maintainable Code

12.1 Requirement

“Store the scores of up to 30 students. Each score must be between 0 and 100. After all scores are entered, display the highest, lowest and average score.”

12.2 Decomposition (AO2)

  1. Read scores (with validation).
  2. Store scores in a list/array.
  3. Calculate highest, lowest and average.
  4. Display the results.

12.3 Structure Diagram

(Main) → ReadScores → AnalyseScores → DisplayResults

12.4 Flowchart (AO2)

(Insert a simple flowchart showing a loop for reading scores, a decision diamond for validation, then processing steps.)

12.5 Pseudocode (with documentation, validation, and modular design)

# Author:  Jane Doe
# Date:    30‑12‑2025
# Purpose: Record student scores and report statistics
# Version: 1.0

CONSTANT MAX_STUDENTS ← 30
CONSTANT MIN_SCORE   ← 0
CONSTANT MAX_SCORE   ← 100

PROCEDURE Main()
    scores ← []                         # empty list
    CALL ReadScores(scores)
    CALL AnalyseScores(scores)
END PROCEDURE

PROCEDURE ReadScores(REF scores)
    WHILE LENGTH(scores) < MAX_STUDENTS
        DISPLAY "Enter score (or -1 to finish): "
        READ inputScore
        IF inputScore = -1 THEN
            EXIT WHILE
        END IF
        IF inputScore < MIN_SCORE OR inputScore > MAX_SCORE THEN
            DISPLAY "Error: score must be 0‑100"
            CONTINUE WHILE               # ask for another value
        END IF
        APPEND inputScore TO scores
    END WHILE
END PROCEDURE

PROCEDURE AnalyseScores(scores)
    IF LENGTH(scores) = 0 THEN
        DISPLAY "No scores entered."
        STOP
    END IF
    highest ← scores[1]
    lowest  ← scores[1]
    total   ← 0
    FOR EACH s IN scores
        IF s > highest THEN highest ← s END IF
        IF s < lowest  THEN lowest  ← s END IF
        total ← total + s
    END FOR
    average ← total / LENGTH(scores)
    CALL DisplayResults(highest, lowest, average)
END PROCEDURE

PROCEDURE DisplayResults(high, low, avg)
    DISPLAY "Highest score : ", high
    DISPLAY "Lowest score  : ", low
    DISPLAY "Average score : ", avg
END PROCEDURE

CALL Main()

12.6 Trace Table for AnalyseScores

Iteration s highest lowest total
0 (initial)90900
190909090
2709070160
3809070240

12.7 Where Validation & Verification Appear

  • Validation – range check in ReadScores guarantees each score is 0‑100.
  • Verification – after AnalyseScores you could add a unit test:
            INPUT scores = [90, 70, 80]
            EXPECT highest = 90, lowest = 70, average = 80
            

13. Maintainability Checklist (AO3)

Checklist Item Yes / No
Consistent 4‑space indentation throughout the file
All identifiers follow the chosen naming convention
Header comment with author, date, purpose and version
Each function/procedure performs a single, well‑defined task
Every function/procedure has a doc‑string or comment describing parameters and return values
Input validation is present for all user‑supplied data
Unit tests exist for all non‑trivial functions
All “magic numbers” are replaced by named constants
Design choices are evaluated and justified (AO3)
Optional: version‑control commits are frequent with clear messages

14. Summary

Creating a maintainable program for the IGCSE requires you to:

  1. Understand the broader computing context (binary data, hardware, software layers, internet security, emerging tech).
  2. Follow the mandatory pseudocode style rules.
  3. Write readable code using consistent indentation and meaningful names.
  4. Document decisions with header comments, inline comments and doc‑strings.
  5. Design modular functions that each solve a single sub‑problem.
  6. Include validation checks to prevent bad input and verification tests to prove correctness.
  7. Test each component (unit) and the whole system (integration), using trace tables where required.
  8. Evaluate and justify every major design decision (AO3).
  9. Optionally use version control to record the evolution of your code.

Mastering these practices will enable you to produce programs that are easy to understand, modify and extend – a key expectation of the Cambridge IGCSE 0478 syllabus and a valuable skill for any future computing work.

Create an account or Login to take a Quiz

59 views
0 improvement suggestions

Log in to suggest improvements to this note.