Persisting an application's data
Keeping state between two launches: text file, CSV or JSON, object serialisation, preferences, embedded database; when to load and when to save; a model that ignores its storage.
- 26 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Persistence: what is it?
Show the answer
The property of data that outlives the program's shutdown because it is written to durable storage.
A variable or an object exists only in working memory: on exit, everything disappears. A file, preferences or a database keep the state from one launch to the next.
What is the exact content of the file
taches.jsonafter this program runs?
```python
import json
taches = [{"titre": "Acheter du pain", "faite": False}, {"titre": "Appeler Ada", "faite": True}]
with open("taches.json", "w") as f:
json.dump(taches, f)`[{"titre": "Acheter du pain", "faite": false}, {"titre": "Appeler Ada", "faite": true}][{"titre": "Acheter du pain", "faite": "false"}, {"titre": "Appeler Ada", "faite": "true"}][{'titre': 'Acheter du pain', 'faite': false}, {'titre': 'Appeler Ada', 'faite': true}]{"titre": "Acheter du pain", "faite": false}, {"titre": "Appeler Ada", "faite": true}
Show the answer
[{"titre": "Acheter du pain", "faite": false}, {"titre": "Appeler Ada", "faite": true}]json.dumptranslates Python types into JSON:Falsebecomesfalse,Truebecomestrue, keys and strings get double quotes, and the list becomes an array in square brackets, with no line break by default.State is loaded at … and saved as soon as it changes, not only on …: a crash or a sudden kill would prevent that last save.
Show the answer
State is loaded at startup and saved as soon as it changes, not only on exit: a crash or a sudden kill would prevent that last save.
Saving at each significant change, or at regular intervals, limits what is lost in an incident.
Serialisation: what is it?
Show the answer
Turning an object into a sequence of bytes or text that can be written to a file or sent over a network.
It picks a format: JSON is readable and language-independent; native Java serialisation produces bytes tied to the class.
A user's preferences are saved with Java serialisation, but their
themefield, markedtransient, comes back asnullat every launch. What must be done to keep it?- Remove
transientfrom the field, since that is what forbids writing it - Declare the field
static, so it is shared between launches - Call the class constructor after the file is read back
- Make the class implement
Serializable, which it does not yet
Show the answer
Remove
transientfrom the field, since that is what forbids writing itA
transientfield is deliberately skipped by serialisation. Astaticfield does not belong to the object and is not written either; and the class is already serialised, since the rest is read back.- Remove