H446/02 · Algorithms & ProgrammingSection 2.1

2.1.2 Thinking ahead

Identifying inputs and outputs, preconditions for solutions, caching and its benefits, reusable program components

📚2.1.2 Thinking Ahead

2.1.2(a) Identify the Inputs and Outputs for a Given Situation

Definition
When designing a solution to a problem, it is crucial to think ahead about the inputs (data provided to the system) and outputs (results produced by the system) required for the program to function correctly.

Understanding Inputs and Outputs

Key Point
CategoryWhat it meansKey design checks
InputsData provided to the system for processingData type, format/order, validation rules
OutputsResults produced after processingClarity, destination (screen/file/device), usefulness

Worked Example
Worked Example: ATM System

InputsPurpose
transactionTypeDeposit / balance check / withdrawal selection
cardDetailsIdentify account via card reader
pinAuthenticate user
amountAmount to deposit or withdraw
OutputsPurpose
------
displayBalanceShow account balance on screen
dispenseCashProvide physical cash
printReceiptProvide transaction record
audioFeedbackAccessibility and confirmation prompts
Why this matters: planning inputs/outputs early prevents security gaps (e.g., no PIN validation) and usability gaps (e.g., no clear confirmation output).

2.1.2(b) Determine the Preconditions for Devising a Solution to a Problem

Definition
Preconditions are specific conditions that must be met before a program or function can execute successfully. They ensure inputs are valid and the program operates without errors.

Purpose of Preconditions

Key Point
Purpose of preconditionsBenefit
Error preventionBlocks invalid states/data before execution
DocumentationMakes function assumptions explicit to other developers
EfficiencyAvoids unnecessary defensive checks deeper in code

Worked Example
Worked Example: Stack Pop with Preconditions

text
function pop(stack):
    // PRECONDITION: Stack is not empty
    if isEmpty(stack) then
        return ERROR("Cannot pop from empty stack")
    end if
    
    item = stack[top]
    top = top - 1
    return item
end function


Without preconditions: The function might crash or return garbage data when popping from an empty stack.

With preconditions: The function handles the error gracefully, returning a meaningful error message.

2.1.2(c) The Nature, Benefits, and Drawbacks of Caching

Definition
Caching is a technique used to store frequently accessed data or instructions in a special memory (cache) for quick retrieval. The goal is to reduce access time from slower storage mediums, thereby improving overall system performance.

Benefits of Caching

Key Point
Caching benefitWhy it helps
SpeedCache access is far faster than secondary storage access
EfficiencyReuses frequent data instead of repeatedly fetching from slow storage
Reduced loadLowers pressure on databases/disks and network resources

Drawbacks of Caching

Key Point
Caching drawbackWhy it is a problem
Cache size limitsSmall caches cannot hold all useful data; very large caches add lookup overhead
Implementation complexityCache policies/prefetching are hard to tune correctly
Data consistency riskCached data can become stale if source data changes
Cache missesMisses force slow fallback to main/secondary storage

Worked Example
Worked Example: Web Browser Caching

StepWhat happens
1User visits www.example.com
2Browser downloads HTML/CSS/images
3Browser stores these files in local cache
4User revisits the page
5Browser serves cached files (if valid) instead of re-downloading
Benefit: faster page load and reduced bandwidth/server demand.

Potential problem: stale content may be shown until cache expiry/refresh.

2.1.2(d) The Need for Reusable Program Components

Definition
Reusable program components are blocks of code (functions, classes, subroutines) designed to be used in multiple programs or different parts of the same program. They are key to efficient software development.

Advantages of Reusable Components

Key Point
Advantage of reusePractical effect
Time/cost efficiencyFaster development with less duplicated work
ReliabilityReused components are often already tested
ConsistencySame behaviour across multiple modules/projects
MaintainabilityOne fix can improve all places where component is used

Challenges

Key Point
Reuse challengePractical impact
Compatibility issuesIntegration can fail across different environments/frameworks
Modification costsAdapting third-party code may be expensive/complex
Learning curveTeam needs time and documentation to use components correctly

Worked Example
Worked Example: Reusable Sorting Component

text
// Reusable sorting function in a library
function quickSort(array, compareFunction):
    // Implementation of quicksort algorithm
    // Thoroughly tested and optimised
end function

// Used in Program A: Sorting student grades
grades = [85, 92, 78, 95, 88]
sortedGrades = quickSort(grades, descending)

// Used in Program B: Sorting customer names
customers = ["Smith", "Jones", "Brown", "Taylor"]
sortedCustomers = quickSort(customers, alphabetical)

// Used in Program C: Sorting products by price
products = [{name: "Book", price: 10}, {name: "Pen", price: 2}]
sortedProducts = quickSort(products, byPrice)


Benefit: The quickSort function is written once, tested thoroughly, and reused across multiple programs without rewriting or retesting.

Exam Tip
Exam Tips for Thinking Ahead:
• Be able to identify inputs and outputs for given scenarios
• Understand the purpose of preconditions and why they matter
• Explain benefits AND drawbacks of caching (don't just list benefits)
• Describe advantages and challenges of reusable components
• Give specific examples for each concept (ATM, stack, web browser, sorting)
• Consider data types appropriate for different inputs