Skip to content
Veltoryx Technologies
ProLesson 2.2Beginner8 min readUpdated 31 October 2026

Encapsulation and Tell, Don't Ask

Learn what encapsulation really protects, why getters and setters everywhere are a warning sign, and how 'tell, don't ask' and the Law of Demeter keep rules in one place.

Think about an ATM. You can press a few buttons, insert your card and take your cash. You cannot reach inside, open the cash drawer and take money yourself. The machine decides whether you may withdraw, checks your balance, and records the transaction. The bank can replace the inside of the ATM completely, and as a customer you would not notice, because the buttons stay the same.

That is encapsulation: an object keeps its data and its rules together, hides the details, and offers a small set of safe actions to the outside. Many beginners think encapsulation means "make the fields private and add getters and setters". That is only the shell of the idea. In this lesson you will learn what encapsulation is really protecting, and a simple habit, tell, don't ask, that makes your designs much stronger.

01What encapsulation protects: the rules

Every real object has rules that must always be true. These are called invariants. For a bank account: the balance must never go below zero. For a shopping cart: the quantity of an item must be at least one. For a booking: the end date must be after the start date.

Encapsulation is how an object defends its invariants. If the data is open for anyone to change, then the rule is only as strong as the weakest caller. Let us see this in an example.

Open data: every caller makes the decision
public class Account {
    private long balance;

    public long getBalance() { return balance; }
    public void setBalance(long balance) { this.balance = balance; }
}
Callers copy the rule, again and again
// In the checkout code
if (account.getBalance() >= amount) {
    account.setBalance(account.getBalance() - amount);
}

// In the transfer code: the rule was forgotten here
account.setBalance(account.getBalance() - amount);

The class looks "encapsulated" because the field is private. But look what happened. The rule "do not go below zero" does not live in Account. It lives in every piece of code that uses an account, and one of them forgot it. The balance can now be negative. Worse, when the rule changes tomorrow (for example, an overdraft limit), you must find and fix every caller.

Loading the rest of the lesson…