Protecting Valid Object State · capstone
Capstone project: Project: Questions and Attempts That Stay Valid
This chapter started with a Question that would happily agree that an empty response was correct. It ends with two classes whose public operations preserve the rules you chose.
The project brings the four tools together on one small program.
What you have to work with
| Tool | Use it when |
|---|---|
Validation in __init__ | An |
| A | Something happened, and several attributes follow from it. |
| A read-only property | Callers need a fact about the object, not a handle on its storage. |
| A property with a setter | One attribute genuinely gets reassigned, and it has a rule. |
Each of the four appears at least once in the finished program. Deciding which belongs where is the work.
The program
You are building the two classes a quiz session needs.
A Question holds a prompt, an answer, and a point value. It refuses to exist without all three. Its points can be adjusted later, but never to zero or below.
An Attempt belongs to one named learner. It absorbs responses through record, which is the only way its results ever change. It reports score, response_count, and accuracy without letting anyone
The starter contains the shell of both classes, a short driver program, and the results it should produce.
An Attempt needs to expose how many points the learner has earned. Which tool fits?
Finishing
A useful last pass before you submit: for each attribute in both classes, ask what would happen if a caller assigned to it right now. If the honest answer is “the object would start lying,” that attribute is not finished.
After the checks pass, you can make the driver yours by replacing the sample questions and learner name with a short quiz you would actually give someone. The checks care about the objects’ behavior, not the subject of the session.
Task
Complete both classes so neither can be pushed into a state it should not have.
Question must refuse construction unless the prompt and answer are non-empty and the points are greater than zero, raising prompt and answer are readable only. Its points is readable and assignable, and refuses zero or less.
Attempt keeps a public learner name. It exposes finished and the three computed values score, response_count, and accuracy as read-only properties. record(question, response) stores the response and its earned points. Changing the question’s points afterward must not change those earlier earnings. finish() ends the attempt, after which record changes nothing.
Submit when the driver program prints the report at the bottom and every refused change leaves the