KS48525 3.2.12 24 min read 10 question quiz 15 exam marks

Robust and Secure Programming

Validation, authentication, defensive design and testing, plus the three kinds of error and how to find each one, written around the idea that a program must survive users who do the wrong thing.

Validation and authentication

Validation checks that data entered is reasonable. It cannot check that data is correct, and knowing the difference is worth marks.

CheckWhat it testsExample
RangeThe value falls between two limitsAn age between 0 and 120
PresenceSomething was actually enteredA name box is not left blank
LengthThe right number of charactersA password of at least 8 characters
TypeThe data is of the expected typeA quantity is a whole number
FormatThe data matches a required patternAn email contains an at sign
Look upThe value is one of a known setA county chosen from a list
Validation cannot detect a lie

A date of birth of 01/01/1990 passes every check you can write, and is wrong if the person was born in 1991. Validation checks plausibility, nothing more. Say that in an exam and you will separate yourself from most candidates.

Authentication

Authentication checks that a user is who they claim to be. Usernames and passwords are the common method, often strengthened by:

  • requiring a minimum length and a mixture of character types,
  • limiting the number of failed attempts before an account is locked,
  • asking for specific characters from a memorable word,
  • two factor authentication, which requires something you know and something you have.

Authentication answers "who are you". Validation answers "is that a sensible thing to type". They are different jobs and questions distinguish them.

Validation checks, and what they cannot doSix validation checks, one card each, with a value that is rejected and a value that is accepted. A presence check makes sure something is entered, so an empty entry is rejected. A type check makes sure the data is the right kind, so the letters abc are rejected for an age. A range check keeps a number between limits, so an age of 200 is rejected. A length check makes sure there are enough characters, so pass is too short for a password of eight or more. A format check makes sure the data matches a pattern, so asha dot com is not an email address without an at sign. A lookup check makes sure the value is one of an allowed list, so Funday is not a day of the week. Two cards underneath separate validation from correctness: validation checks data is sensible, not that it is true, so an age of 15 mistyped as 51 passes a range check and is still wrong. Verification checks that data was entered as intended, for example by typing a password twice and comparing.Presencesomething must be entered""AshaTypethe right kind of data"abc"15Rangebetween two limits (0 to 120)20015Lengthenough characters (8 or more)"pass""pass1234"Formatmatches a pattern"asha.com""asha@mail.com"Lookupone of an allowed list"Funday""Friday"1Valid is not the same as trueAge 15 mistyped as 51 is in range,so every check passes and thedata is still wrong.validation checks it is sensible, not that it is trueVerification: typed twicepasswordenter itconfirmand enter it againdo they match?23
  1. Validation checks: presence, type, range, length, format and lookup.
  2. Validation checks that data is sensible. It cannot know whether it is true.
  3. Verification asks the user again, for example with a confirm password box, to catch typing slips.
Validate on the way in, and tell the user what is wrong, not just that something is.
Authentication: what you know, have and are, and how passwords are keptAuthentication proves who someone is, using three kinds of evidence, one card each: something you know, such as a password or PIN; something you have, such as a phone showing a one time code, a bank card or a key fob; and something you are, such as a fingerprint or a face. Using two of them together, two factor authentication, is far stronger than one. The login flow shows it: the user enters a username and password, a code is sent to their phone, and only then is access granted, so a stolen password alone is not enough. Underneath, a password should never be stored as typed. The system keeps only a hash, the output of a one way function, so password123 is stored as a string of characters such as 5f4dcc3b and the real password is never kept. If the file is stolen, it does not reveal the passwords.Something you know• • • • • • • •password, PINSomething you have482 913codephone, bank card, key fobSomething you arefingerprint, face1Two-factor loginusername +passwordcode sent toyour phoneaccessgranteda stolen password alone is not enoughthe second factor is something an attacker does not have2Stored as a hashpassword123hash function5f4dcc3b5aa765d6...the real password is never kept,so a leak does not reveal it3
  1. Three kinds of evidence: something you know, have or are.
  2. Two factors together are far stronger than one: a stolen password alone is not enough.
  3. Passwords should be stored as hashes, never as typed, so a leak does not reveal them.
Strong authentication is layers. No single one of them is enough alone.

Defensive design and maintainability

Defensive design means writing a program that keeps working when things go wrong, rather than one that only works when everything goes right.

Anticipate misuse. Assume every input will eventually receive an empty string, a negative number, a word where a number was expected and a value a thousand times larger than you planned for. Handle each of those deliberately.

Fail helpfully. A message saying what was wrong and what to do lets the user recover. A crash does not.

Authenticate before acting. Check permission before doing anything sensitive, not after.

Maintainability

Maintainable code is code that another programmer, or you in a year, can safely change.

  • Meaningful identifiers. totalPrice rather than tp or x2.
  • Comments that explain why, not what. count ← count + 1 does not need a comment saying it adds one. It might need one saying why the first record is skipped.
  • Indentation that reveals structure, so the body of a loop is visibly inside it.
  • Subroutines so each task lives in one named place.
Comments are examined

A question asking how a program could be made more maintainable expects specific examples, so name a poor identifier in the code you have been given and say what you would rename it to.

Testing and the three kinds of error

Syntax errors

A syntax error breaks the rules of the language, such as a missing bracket or a misspelled keyword. The program will not run at all, and the translator reports the error, usually with a line number.

Logic errors

A logic error means the program runs perfectly and produces the wrong answer. Using + where you meant -, or < where you meant ≤, gives a logic error. Nothing reports it, which is precisely why these are the expensive ones.

Runtime errors

A runtime error happens while the program is executing: dividing by zero, reading past the end of an array, opening a file that does not exist. The program starts and then stops.

Test data

Every test plan needs three kinds of data, and AQA asks for them by name.

TypeMeaningExample for an age between 0 and 120
NormalTypical data the program should accept35
BoundaryData at the very edge of what is acceptable0, 120, and just outside, -1 and 121
ErroneousData the program should reject"cat", an empty entry, 3.5
Boundary data is where the bugs live

Almost every off by one error shows up at a boundary and nowhere else. A program tested only with 35 will pass while rejecting every newborn and accepting every age up to 121.

Iterative and final testing

Iterative testing happens during development, module by module, so faults are found while the code is still fresh and small. Final testing happens once the program is complete and checks the whole thing against the original requirements. Both are needed: iterative testing finds faults cheaply, final testing proves the program does the job it was asked to do.

The three kinds of error: syntax, runtime and logicThe three kinds of programming error, one card each, each with its own bug. A syntax error breaks the rules of the language, like print with an opening bracket that is never closed. The translator cannot understand the line, reports a SyntaxError and the program will not start. A runtime error happens while the program is running: dividing 10 by 0 makes the program start and then crash on that line with a ZeroDivisionError. A logic error is the hardest to find because nothing crashes: the program average equals a plus b divided by 2 runs happily and prints 8.0, when the average of 4 and 8 is 6.0, because division is done before addition. Only testing against the answer you expected finds it.Syntax errora typo in the rules of the languageprint("Hello"resultSyntaxError:'(' was never closedfound how?found before it runs,by the translatorRuntime errorthe program starts, then crashesx = 10 / 0resultZeroDivisionError:division by zerofound how?found while it runs:it stops on that lineLogic errorruns fine, gives a wrong answera, b = 4, 8average = a + b / 2print(average)result8.0(should be 6.0)found how?found only by testing againstthe answer you expected123
  1. Syntax error: the code breaks the rules of the language, so it will not run at all.
  2. Runtime error: the program starts, then crashes when it meets something it cannot do.
  3. Logic error: it runs without complaint but gives the wrong answer, so only testing finds it.
A program that runs is not a program that is right. Test the answers, not only the absence of crashes.
Normal, boundary and erroneous test dataTest data for a program that asks for an age from 13 to 19. A number line shows the valid range in green, from 13 to 19, and the invalid values in red either side. Normal data is a typical value inside the range, such as 16. Boundary data sits on the edge of what is allowed and just outside it: 13 and 19 are the two valid boundaries and 12 and 20 are the first invalid values either side. Erroneous data is the wrong type or not sensible at all, such as the text abc, a negative number or an empty entry. Beneath, a test plan lists each test with its data, type, expected result and actual result. The first three pass. The fourth, the text abc, was expected to make the program ask again but the program crashed, so it fails, and that points to a missing validation check.Test data for: enter an age from 13 to 1901213161920invalidvalidinvalidnormal: 16boundary: 12, 13boundary: 19, 20erroneous:"abc"-5emptythe wrong type, or not a sensible value123A test plan, with the result of each testTestDataTypeExpectedActualPass?116normalacceptedaccepted213boundaryacceptedaccepted312boundaryrejectedrejected4"abc"erroneousasks againcrashes4
  1. Test data for an age from 13 to 19, on a number line.
  2. Normal data is typical and should be accepted.
  3. Boundary data sits on and just outside each edge, because that is where mistakes hide.
  4. A test plan records expected against actual. A failed test shows what to fix.
Always test at the boundaries, on both sides of each one.

Key terms you must be able to define

Validation
An automatic check that data entered is reasonable and of the expected form.
Authentication
Checking that a user is who they claim to be, usually with a username and password.
Range check
A validation check that a value falls between an upper and a lower limit.
Presence check
A validation check that a required value has actually been entered.
Format check
A validation check that data matches a required pattern.
Syntax error
An error that breaks the rules of the programming language, preventing the program from running.
Logic error
An error in which the program runs but produces the wrong result.
Runtime error
An error that occurs while the program is executing, causing it to stop.
Normal test data
Typical data that the program should accept and process correctly.
Boundary test data
Data at the very edge of the acceptable range, on both sides of the limit.
Erroneous test data
Data the program should reject, used to check the validation works.
Iterative testing
Testing carried out repeatedly during development as each part is written.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineValidation
AnswerAn automatic check that data entered is reasonable and of the expected form.
DefineAuthentication
AnswerChecking that a user is who they claim to be, usually with a username and password.
DefineRange check
AnswerA validation check that a value falls between an upper and a lower limit.
DefinePresence check
AnswerA validation check that a required value has actually been entered.
DefineFormat check
AnswerA validation check that data matches a required pattern.
DefineSyntax error
AnswerAn error that breaks the rules of the programming language, preventing the program from running.
DefineLogic error
AnswerAn error in which the program runs but produces the wrong result.
DefineRuntime error
AnswerAn error that occurs while the program is executing, causing it to stop.

Reach the top grade on this topic

The strongest answers here understand what each technique can and cannot do.

They limit validation honestly. A grade 9 answer says validation confirms data is plausible, and explicitly adds that it cannot confirm data is true. That single sentence appears in mark schemes.

They choose test data with a reason. Not "I would test with 0 and 120" but "I would test with 0 and 120 because they are the boundaries, and with -1 and 121 because an off by one error in the comparison would only show up there".

They tell the three errors apart by symptom. Will not run at all is syntax. Runs and gives the wrong answer is logic. Starts and then stops is runtime. Answering by symptom rather than by definition shows understanding.

Mistakes that cost marks here

Avoid these
  • Saying validation makes sure data is correct. It makes sure data is reasonable.
  • Confusing validation with verification. Verification checks data was entered accurately, for example by typing it twice.
  • Giving only one boundary value. A boundary needs testing on both sides of the limit.
  • Calling a crash a logic error. If the program stops while running it is a runtime error.
  • Writing comments that restate the code. A useful comment explains why, not what.
Fun fact

In 1996 the first Ariane 5 rocket destroyed itself 39 seconds after launch. The cause was a 64 bit real number being converted into a 16 bit integer that could not hold it, in code that was not even needed after lift off.

Knowledge check

0 of 10 answered
1A program will not run and the translator reports a missing bracket. What kind of error is this?
2A program runs but calculates the average by dividing by the wrong number. What kind of error is this?
3Which validation check would stop a user leaving a name box empty?
4For an input that must be between 1 and 10, which set is boundary test data?
5What can validation never do?
6What is the purpose of authentication?
7A program stops with an error when it tries to open a file that has been deleted. What kind of error is this?
8Which of these most improves the maintainability of a program?
9Why is iterative testing carried out during development rather than only at the end?
10What is erroneous test data used to check?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

15 marks
1State what is meant by validation.1 mark
State

Mark scheme0 / 1
  • LAn automatic check that data entered is sensible or reasonable
Model answer

Validation is an automatic check carried out by a program to make sure that data entered is reasonable and of the form expected.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2A program asks for a percentage mark between 0 and 100. Give one item of normal test data, one item of boundary test data and one item of erroneous test data.3 marks
Give

Mark scheme0 / 3
  • LNormal data is a typical value inside the range, such as 55
  • LBoundary data is at the edge of the range, such as 0, 100, -1 or 101
  • LErroneous data is something that should be rejected, such as a word or a blank entry
Model answer

Normal test data would be 55, a value comfortably inside the acceptable range that the program should accept. Boundary test data would be 0 and 100, the two limits, together with -1 and 101 just outside them, since an incorrect comparison would only show up there. Erroneous test data would be a word such as cat, or a blank entry, which the program should reject rather than process.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain the difference between a logic error and a syntax error.4 marks
Explain

Mark scheme0 / 4
  • LA syntax error breaks the rules of the programming language
  • LA program containing a syntax error will not run, and the translator reports it
  • LA logic error means the program runs but produces the wrong result
  • LNothing reports a logic error, so it must be found by testing or by tracing the program
Model answer

A syntax error breaks the rules of the programming language, for example a missing bracket or a misspelled keyword. The translator cannot make sense of the line, so the program will not run at all and the error is reported, usually with a line number, which makes it comparatively easy to fix. A logic error is different in kind. The code is perfectly valid, so the program translates and runs, but the instructions do not do what the programmer intended, so the output is wrong. Nothing reports it, which means it can only be found by testing with data whose correct answer is already known, or by tracing the program by hand.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A shopping website validates the postcode a customer enters. Explain why validation alone cannot guarantee the parcel will arrive.3 marks
Explain

Mark scheme0 / 3
  • LValidation only checks that the data is of a reasonable form
  • LA postcode can be correctly formatted but not be the customer's actual postcode
  • LValidation cannot check truthfulness, only plausibility
Model answer

Validation checks the shape of the data, so a format check can confirm that the entry looks like a postcode and a look up check can confirm that it is a postcode that exists. Neither of those establishes that it is the right postcode for this customer. Somebody can enter a real, correctly formatted postcode belonging to a different address, either by mistake or deliberately, and every check will pass. Validation tests whether data is plausible, and no automatic check on the data alone can test whether it is true.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Describe two ways in which a programmer can make a program easier to maintain.4 marks
Describe

Mark scheme0 / 4
  • LUse meaningful identifier names that say what the value holds
  • LSo another programmer can understand the code without tracing it
  • LUse comments to explain why the code does what it does
  • LUse subroutines and indentation so the structure is visible and each task lives in one place
Model answer

The first is to use meaningful identifiers. A variable called totalPrice tells the next reader what it holds, whereas one called tp or x2 has to be traced through the whole program before it can be safely changed. The second is to use subroutines with sensible indentation, so that each task lives in one named place and the structure of the program is visible on the page. Together those mean that a change to how something is calculated is made once, in an obviously named place, with far less risk of breaking something elsewhere. Comments explaining why an unusual decision was taken support both.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 15