A variable is a named storage location or binding whose value can be read or changed during execution. In readable code, variables act like characters in a story: their names, timing, and scope determine how easily readers follow the action. section 2.4
Shape variables around the story the code needs to tell:
- Introduce important variables early when they carry the method’s main plot. section 2.4
- Declare secondary variables as close as possible to their use, preferably with the smallest practical scope. section 2.4
- Name variables for intent: nouns usually represent data, collections are commonly plural, and booleans read naturally as questions. section 2.4
- Treat too many temporary variables or intermediate steps as a signal to separate concerns into clearer scenes or methods. section 2.4
Remove unnecessary mutable state
A promotional-email method initially declares emailContent before branching, duplicates promotion lookups, assigns the result in each branch, and returns it afterward. A clearer version obtains the user and promotions once, checks the birthday inline, and returns the appropriate email directly. The improved structure keeps variables close to their purpose and removes a mutable result variable. section 2.4 section 2.6
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;
}
Inspect the scene-level method that builds promotional email content and observe how its variables support the method’s central action. section 2.4
Mutable variables can also make simple mappings fragile. A traditional Java switch may require a variable, repeated assignments, breaks, and a final return; a missing break can overwrite the intended value. Prefer a variable only when it clarifies the transformation rather than merely carrying control-flow mechanics. section 5.1.1










