Low-level design›Encapsulation: guarding an object's data
Tutorial 2 of 8 · Low-level design · Building blocks · IntermediateEncapsulation: guarding an object's data
Keep an object's data private and let only its own methods change it, so it can never break its own rules.
5 lessons, the last is a challenge · about 1 h · Python and Java
Before you startYou finished "Reading and drawing class diagrams": you can read a class box with its fields and methods.
You can write a class with a constructor, fields and methods in Python or Java, and catch an error with try, as in the Programming fundamentals path.
What you’ll be able to do
- 1Say what goes wrong when any code can change an object's fields, and what encapsulation means: only the object's own methods change its data.
- 2Make a field private in Java or mark it with an underscore in Python, and say what each language does when outside code touches it.
- 3Let outside code read a private field through a getter or a Python property, with no setter, and return a copy of a list instead of the list itself.
- 4Write a class whose data can only change through methods that check every change, so that it keeps its invariant after every call.
Lessons
Next in this path
Next: 3 · Composition over inheritance · 5 lessons · 1 h 05 min
Build a class out of parts it holds instead of a parent it copies, and swap the parts when needs change.
Playground
Try the same model with your own values. No checks, nothing recorded.
Open the playground