Refactoring improves the internal structure and design of existing code without changing its external behavior. It is a way to make working code safer to change and easier to understand. section 3.3.1
A client that repeatedly asks a service for low-level data and performs the work itself may signal tight coupling. Moving that process into the service gives the client a simpler conversation and keeps the details encapsulated. section 3.3.1
From interrogation to conversation
A report generator first fetches user details and order totals through several service calls. After restructuring, the service provides aggregated data and the client formats the report. 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)}`;
}
}Inspect the original service-client interaction and spot the repeated low-level requests. section 3.3.1
Listing 3.2 The Refactored “Conversation”
// --- The Refactored "Service" Class ---
class UserDataService
{
// The Service provides a single, high-level data aggregation method
getUserSummaryData(userId)
{
return { ... }; #A
}
}
// --- The Refactored "Client" Class ---
class UserReportGenerator
{
constructor() { this.dataService = new UserDataService(); }
generateReport(userId)
{
const report = this.dataService.getUserReport(userId); #B
return `User Report for ${report.name} (${report.email}) -
Total Spent: $${report.TotalSpent.toFixed(2)}`;
}
}Compare the refactored version, where the service handles aggregation and the client makes a high-level request. section 3.3.1




























