Encapsulation
Инкапсуляция
An object or module keeps its data together with the operations that manage it. Other code uses a defined interface instead of reaching into the implementation or changing the data directly.
What encapsulation means
A shopping cart lets you add an item, remove one, or ask for the total. You don't need to know whether it stores items in a list or a map. More importantly, you don't need to remember to update the total yourself after adding an item. The cart owns its state and provides operations that take care of the rules for changing it.
How the boundary works
The public interface is what callers are expected to use. The implementation is how the object or module delivers that behavior. Keeping these separate lets you change the implementation without rewriting caller code, provided the interface and its promised behavior stay the same. A queue, for example, can switch its underlying storage without changing the order in which it returns items.
Encapsulation also gives you a place to enforce invariants: conditions that must hold whenever an object is in a valid state. Constructors establish those conditions, and operations that change state preserve them. You don't need a class to set such a boundary: a module can keep its data unexported and expose functions that manage it.
Example: reserving seats in JavaScript
class Seats {
#remaining;
constructor(capacity) {
if (!Number.isSafeInteger(capacity) || capacity < 0) {
throw new RangeError('Expected a non-negative safe integer');
}
this.#remaining = capacity;
}
reserveOne() {
if (this.#remaining === 0) return false;
this.#remaining--;
return true;
}
get remaining() {
return this.#remaining;
}
}
The invariant is that the number of seats remaining is a non-negative integer. The constructor rejects invalid starting values, and reserveOne() leaves the count unchanged when no seats are available. Calling code can read seats.remaining, but the #remaining field is private to the class. There's no public setter that can make the count negative.
Common mistakes
Marking a field private is only one step. Suppose a cart has a private array but its items getter returns that very array. A caller can clear it without going through removeItem(), potentially leaving a cached total out of date. Returning a copy prevents callers from changing the original array's membership through the copy, but a shallow copy still shares any item objects. Decide what callers actually need to inspect before exposing internal data.
What interviewers look for
When shown a class with public fields or a getter and setter for everything, don't just suggest adding private. Identify a rule the class should enforce, show how a caller could break it, and propose a narrower interface. In the seat example, reserveOne() expresses the action and owns the availability check; setRemaining() would make callers responsible for deciding what the new count should be.