lesson

Keep a rule true after every operation

1 · Learn

Program state is the information currently held. An invariant is a condition intended to remain true at defined points, such as an inventory count never becoming negative. Each operation must preserve it or reject an invalid request.

Checking only when a screen first opens is insufficient if later actions can break the rule. Identify where state changes occur.

StateInvariantOperationValidation
Key words and supplied examples.

2 · Worked example

If stock is 3, a request to remove 5 must not simply leave -2 when the invariant forbids negative stock.

3 · Your turn

Starting at stock 3, what should happen to a request to remove 5 under that invariant?

Check your answer

Reject the request or otherwise handle it explicitly without storing a negative count.

4 · Apply your learning

Trace add and remove operations, including boundary cases, and verify the invariant after each.

Adult guidance and safety

Work in an approved local sandbox with invented records and test accounts. Do not access other people's systems or collect real credentials. Practical project evidence is required in addition to these explanations; this is not a specified GCSE Computer Science course.

Practice this lesson

Lesson resources

Browse the available practice activities and worksheets for this lesson.

Open course resources
Exercise preview