Implement Private Class Data in Java by hiding internal state holders and exposing only the operations needed to maintain invariants.
Private Class Data: A pattern that protects internal state by grouping it behind a narrow public API instead of exposing the state structure directly.
In Java, a simple implementation often uses a private immutable state holder.
1public final class BankAccount {
2 private record State(String id, Money balance, AccountStatus status) {}
3
4 private State state;
5
6 public BankAccount(String id, Money openingBalance) {
7 this.state = new State(id, openingBalance, AccountStatus.OPEN);
8 }
9
10 public Money balance() {
11 return state.balance();
12 }
13
14 public void deposit(Money amount) {
15 state = new State(state.id(), state.balance().add(amount), state.status());
16 }
17}
Clients do not see the state shape directly. They see operations and selected read access.
This pattern is useful when:
If the internal data structure is part of the class’s invariants, hide the structure and expose behavior or carefully chosen queries instead.