Scope defines where a name or binding can be accessed. Keep each variable within the smallest region that needs it, and place its declaration close to its use. section 2.4
Treat variables as characters in a readable code story: important characters appear early, while secondary characters enter only in the scene where they matter. Narrow scope reduces competing temporary details and keeps the central logic visible. section 2.4
Move scene-specific variables into the scene
A promotional-email method first declares emailContent and separate birthdayPromotions or standardPromotions inside conditional branches. A clearer version loads promotions once, keeps it near its use, and returns directly from each branch. The narrower arrangement removes unnecessary state and makes the method’s two outcomes easier to follow. section 2.4
Listing 2.6 Scene-level method building promotional email content
public String buildPromotionalEmailContent(long userId) {
String emailContent; #1
User user = userService.findUserById(userId); #2
boolean isUserBirthday = isToday(user.getBirthday());
if (isUserBirthday) {
List<Promotion> birthdayPromotions = #3
promotionService.getPromotionsFor(user); #3
emailContent = birthdayPromotionEmailFor(user, birthdayPromotions);
} else {
List<Promotion> standardPromotions = #3
promotionService.getPromotionsFor(user); #3
emailContent = regularPromotionEmailFor(user, standardPromotions);
}
return emailContent;
}
Compare the original scene-level method with its improved form to see how declaration placement and block scope reduce clutter. section 2.4




















