Defensive design

GCSE Computer Science (OCR) · OCR J277 · 2.3.1 · Algorithms and programming (Paper 2) › Producing robust programs

66 exam-style questions plus unlimited generated ones on this topic, at up to four difficulty levels, with full mark schemes. Notes and past-paper booklets are open to everyone. Practice needs a free account.

Or take a quick quiz: 11 questions on this subtopic in GCSE Computer Science (OCR), marked as you tap.

Revision notes

Defensive design means planning a program so that it copes with misuse, only lets the right people in, checks its inputs and is easy for other programmers to maintain. Expect questions on validation checks, authentication, maintainability and writing validation code.

Key facts

  • Anticipating misuse: plan for unexpected input and attempts to break or break into the program
  • Authentication: confirming who the user is (username and password, limited attempts)
  • Validation: checks input is sensible or allowed before it is used (not that it is correct)
  • Range check: between limits; type check: correct data type
  • Length check: number of characters; presence check: not blank
  • Format check: follows a pattern, such as DD/MM/YYYY
  • Maintainability: sub programs, meaningful names, indentation, comments

Notes

Anticipating misuse and authentication

  • Anticipating misuse: thinking ahead about how users might enter unexpected data, or try to break into or crash the program, and designing the program to cope. Examples: blank inputs, text where a number is expected, very large values, dividing by zero, trying passwords over and over.
  • Authentication: confirming the identity of a user before they get access, for example with a username and password.
  • Authentication can be made stronger by limiting the number of login attempts, locking the account after several failures, and not saying which of the username or password was wrong.

Input validation

diagram
  • Validation checks that input data is sensible and follows the rules before the program uses it.
  • Range check: the value is between set limits (an age from 11 to 18).
  • Type check: the data is the correct data type (a whole number, not text).
  • Length check: the number of characters is allowed (a password of at least 8 characters).
  • Presence check: something has been entered (the field is not blank).
  • Format check: the data follows a pattern (a date written as DD/MM/YYYY).
  • Validation cannot check the data is correct: a valid but wrong date of birth is still accepted.
  • Example:
    age = int(input("Enter age (11 to 18)"))
    while age < 11 OR age > 18
       print("Invalid age")
       age = int(input("Enter age (11 to 18)"))
    endwhile
  • StartInput ageage < 11 ORage > 18?YesOutput"Invalid age"Noage is valid: use it
    The validation loop in the example, as a flowchart

Maintainability

  • Maintainable code is easy for another programmer (or you, later) to understand, fix and update.
  • Sub programs split the code into small, named parts that can be understood and tested one at a time.
  • Naming conventions: meaningful identifiers, such as totalCost instead of t, show what each variable holds.
  • Indentation shows which lines are inside each loop or if statement.
  • Comments explain what sections of code do and why.

How to answer each type of question

Identify and describe validation checks

2 to 4 marksGrade 4
  1. Name the check that fits the data.
  2. Describe exactly what it checks, using the values in the question.

Example. A sign-up form asks for a username, which must be 6 to 12 characters long, and an age, which must be from 13 to 99.
Identify a suitable validation check for each input and describe what it checks. [4]

Show the model answerHide the model answer
Username: length check (1), which checks the username has from 6 to 12 characters
(1).
Age: range check (1), which checks the age is from 13 to 99
(1).

Write validation code

3 to 4 marksGrade 6
  1. Input the value.
  2. Use a loop that repeats while the value is invalid (or until it is valid).
  3. Input the value again inside the loop, with an error message if asked.
  4. Check the condition includes the limits correctly.

Example. Write an algorithm that asks the user to enter a quantity, and keeps asking until a whole number from 1 to 20 is entered. [3]

Show the model answerHide the model answer
do
   qty = int(input("Enter quantity (1 to 20)"))
until qty >= 1 AND qty <= 20
A loop that repeats until the input is valid (1); the input is inside the loop (1); the condition accepts only 1 to 20 inclusive (1).

Improve the maintainability of code

2 to 4 marksGrade 5
  1. Look for single-letter names, no indentation and no comments.
  2. State an improvement that applies to this code.
  3. Explain how it helps another programmer.

Example. Give two ways the maintainability of this code could be improved, and explain how each helps.

a = 0
for b = 1 to 10
c = int(input("?"))
a = a + c
next b
print(a / 10)
[4]

Show the model answerHide the model answer
Use meaningful variable names, such as total instead of a (1), so the purpose of each variable is clear
(1).
Indent the lines inside the loop (1) so it is clear which lines are repeated
(1).
Also accept: add comments (1) to explain what the code does
(1).

Explain how to reduce misuse

2 to 4 marksGrade 7
  1. Give a design feature, such as limiting login attempts or validating inputs.
  2. Explain what misuse it prevents.
  3. Link it to the scenario.

Example. An online game requires players to log in. Describe two ways the login system could be designed to reduce misuse. [4]

Show the model answerHide the model answer
Limit the number of password attempts, locking the account after, say, three failures (1), which stops someone guessing passwords over and over
(1).
Validate every input, such as checking the username is not blank and not too long (1), so unexpected data cannot cause errors or crash the program
(1).

Don’t lose marks

  • Naming a check without describing it with the values from the question.
  • Choosing a range check for text, or a length check for a number range.
  • Writing validation with an if statement only, so the user is never asked again.
  • Getting the loop condition backwards (repeating while the data is valid).
  • Saying comments make the program run better: they only help people read the code.

More tips

Memory tricks

  • Validation checks: 'Really Tidy Little Pupils Follow' = Range, Type, Length, Presence, Format.
  • Maintainability: 'SNIC' = Sub programs, Naming, Indentation, Comments.
  • Valid is not the same as correct: validation checks the data is sensible, not true.

Exam technique

  • When a check is asked for, name it AND describe it for this data.
  • In validation code, test your condition with a value just inside and just outside each limit.
  • For maintainability, the four OCR terms are sub programs, naming conventions, indentation and commenting: use them.

What each grade needs

What you need to be able to do, from the first marks up to the top grade.

  1. Grade 3
    Name types of validation checkRange, type, length, presence and format checks.
  2. Grade 4
    Choose a suitable validation checkMatch the check to the data, such as a range check for an age.
  3. Grade 5
    Describe ways to make code maintainableSub programs, meaningful names (naming conventions), indentation and comments.
  4. Grade 5
    Explain what authentication isChecking that users are who they say they are, for example with a username and password.
  5. Grade 6
    Write validation code with a loopKeep asking for the input until it meets the rule, giving a message if it is invalid.
  6. Grade 7
    Explain how to anticipate misusePlan for unexpected input, repeated login attempts and people trying to break the program.
  7. Grade 8
    Explain the limits of validationValidation checks data is sensible, not that it is correct.

Quick recall

Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.

State the name of this type of validation check.
Range check
State the name of the type of validation check that checks the pattern of letters and digits.
Format check
State what is meant by the maintainability of a program.
How easily a program can be understood, fixed and changed by a programmer.
Give one reason why a programmer adds comments to a program.
To explain what the code does so that it is easier to understand and maintain.
A programmer names the variables in a program playerName, totalScore and highScore, using the same style for every name. State one benefit of using a naming convention like this.
Names are consistent, so the code is easier to read and understand.
Look at this program.
01 name = input("Enter your name")
02 if name == "" then
03     print("Name required")
04 else
05     print("Hello " + name)
06 endif
State the output if the user presses Enter without typing anything.
Name required

Sample questions

Written for this site in the style of OCR exam questions. They are not taken from real past papers.

Question 1Easy3 marks
(a) State what is meant by authentication.
[1]
(b) Give one method of authentication.
[1]
(c) Give one way that a programmer can anticipate misuse of a program.
[1]
Show the answer and mark scheme
(a)
  • confirming / checking the identity of a user (before they are allowed to access the program or data)
(b)
  • username and password / PIN / fingerprint or other biometric / a code sent to a phone (two-factor authentication)
(c)
  • validate every input
  • limit the number of login attempts
  • check for unexpected inputs, e.g. text where a number is expected / blank inputs
  • prevent errors such as dividing by zero
Question 2Medium6 marks
Look at this program.
01 // Works out the price after a percentage discount
02 function discountedPrice(price, percent)
03    discount = price * percent / 100
04    return price - discount
05 endfunction
06 
07 // Main program
08 itemPrice = float(input("Enter the price"))
09 print(discountedPrice(itemPrice, 15))
Identify three features of the program that make it easier to maintain. For each feature, explain how it helps.
[6]
Show the answer and mark scheme
  • comments (lines 01 and 07)
  • explain what the code does, so another programmer can understand it quickly
  • meaningful / descriptive identifiers, e.g. discountedPrice, itemPrice
  • make the purpose of each variable and sub program clear
  • indentation (lines 03 and 04)
  • shows which lines belong inside the function / makes the structure clear
  • use of a sub program (function)
  • the code can be reused and only needs to be changed in one place
Question 3Hard8 marks
A program stores a user's username and password in the variables storedUser and storedPass.
(a) Write an algorithm that:
  • asks the user to enter a username and a password
  • allows a maximum of three attempts
  • outputs Welcome if the username and password both match the stored values
  • outputs Account locked after three failed attempts.
You must use either OCR Exam Reference Language or a high-level programming language that you have studied.
[6]
(b) Explain why the program should not tell the user whether it was the username or the password that was wrong.
[2]
Show the answer and mark scheme
(a) Answer:
attempts = 0
success = false
while attempts < 3 AND success == false
   user = input("Username")
   password = input("Password")
   attempts = attempts + 1
   if user == storedUser AND password == storedPass then
      success = true
   endif
endwhile
if success then
   print("Welcome")
else
   print("Account locked")
endif
  • inputs a username and a password inside the loop
  • compares both with the stored values using AND
  • counts the number of attempts
  • the loop ends when the details are correct OR three attempts have been used
  • outputs Welcome when the details match
  • outputs Account locked after three failed attempts
(b)
  • an attacker would learn that a username is valid
  • so they would only need to guess the password, making the account easier to break into

More in Producing robust programs

Stuck? Get 1-to-1 help.

Chhetri Academy tutors GCSE and A level Maths and Science online, with a free 30-minute trial lesson.