A smartphone lets you change a setting through its screen, not by poking at its wiring. Encapsulation applies the same idea to software: keep data and the methods that manage it together, and let other code interact through a public interface rather than uncontrolled access to internal state. section 3.4
Encapsulation also keeps a process’s “how” with the component responsible for it. If a client must fetch several pieces of data and perform the service’s calculations itself, the service’s process has leaked into the client. A higher-level request lets the service manage that complexity. section 3.3.1
Listing 3.1 Coupling Test
// --- The "Service" Class ---
class UserDataService
{
getUserName(userId) { return "Jane Doe"; }
getUserEmail(userId) { return "jane.doe@example.com"; }
getUserOrderIds(userId) { return [ "A123", "B456" ]; }
getOrderTotal(orderId) { return 99.95; }
}
// --- The "Client" Class ---
class UserReportGenerator
{
constructor() { this.dataService = new UserDataService(); }
generateReport(userId) #A
{
const name = this.dataService.getUserName(userId); #A
const email = this.dataService.getUserEmail(userId); #A
const orders = this.dataService.getUserOrderIds(userId); #A
let totalSpent = 0;
for (const orderId of orders)
{
totalSpent += this.dataService.getOrderTotal(orderId); #B
}
return `User Report for ${name} (${email}) -
Total Spent: $${totalSpent.toFixed(2)}`;
}
}See the problem in action: the report generator fetches order IDs and totals individually, then calculates the total itself. section 3.3.1
A simpler conversation
Instead of interrogating the data service for each detail, a report generator can request a user summary. The service owns the aggregation; the client formats the result. If the calculation changes, the change can stay in the service rather than spreading to the report generator. section 3.3.1
An order that protects its state
An Order that only stores fields leaves other code free to set its total to -100. Keeping behavior such as validation and total calculation with the order’s data helps it protect its own state instead of relying on scattered controller logic. section 4.7.2
Try the simple conversation test: does one component make a few clear requests, or does it interrogate another for details and orchestrate its work? An interrogation is a candidate for refactoring. Encapsulation can reduce coupling, cognitive load, and the reach of future changes. section 3.3.1
The same boundary matters with external services. When checkout logic exposes raw network details throughout an application, changes to a payment provider can force changes in the core workflow and make tests depend on the live network. section 10.4.1
















