← Path
Object-Oriented Programming · Object-Oriented Programming: Classes, Objects and Encapsulation
0 XP- 1 current stop: learning
- 2 upcoming
- 3 upcoming
- 4 upcoming
- 5 upcoming
Finish after stop 5
Stop 1 of 5 · Ticket counter at the metro
Trick to keep in mind+3 XP
Don't just hide the field: make the class the only gatekeeper of its own rule.
Every class has an invariant, a fact that must always hold, such as a balance never dropping below zero. Encapsulation means the object itself defends that fact on every path that changes its data. A comment is only a request, a setter that just assigns the field defends nothing, and a check in one screen leaves every other caller unguarded.
Read it once, then a question tests whether the trick stuck.