Software design and clean code

Stage 1 · Lesson 2 of 8

Encapsulation and invariants

Object-oriented programming properly

means hiding an object's internal state behind a small set of methods. An is a rule that must always be true for the object, such as a balance never going negative or an order total always matching its lines. If the only way to change the balance is a deposit method that rejects bad amounts, the rule holds everywhere, forever.

You can also change how the data is stored without touching any caller. Make fields private by default and expose behaviour, such as withdraw, rather than raw data, such as setBalance.

Common trapgenerating a getter and a setter for every field out of habit, which makes the field public in all but name and leaves the rules unprotected.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

Practise

  • Free exercises in your language with optional human mentoring on design, not just on passing tests

Keep handy

  • Oracle's own tutorials on classes, interfaces, records and sealed classes in current Java

Also worth your time

Mark this stage as not done?