liveBook · Manning

Variable naming

As explained in The Art of Code

Variable naming is the practice of choosing identifiers that accurately and consistently communicate the purpose of stored values.

Good variable names make stored values read like characters in a story: they reveal purpose, reduce cognitive load, and warn against careless changes. section 2.4

Use names that communicate both the value and its role:

  • Prefer nouns for data, plural nouns for collections, question-like names for booleans, and verbs for action-oriented lambdas. section 2.4
  • Choose domain vocabulary consistently; switching between terms such as client, user, and visitor creates confusion. section 2.4
  • Avoid single-letter, generic, or ambiguous names such as x, temp, flag, and data, except for familiar loop variables. section 2.4
  • Keep variables near their use and within the smallest possible scope; excessive temporaries can obscure the central logic. 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 crowded promotional-email method with its clearer revision: descriptive names, localized scope, and fewer intermediate variables expose the main flow. section 2.4

How The Art of Code covers it

How deep it goes
Explains naming patterns, scope, consistency, and cognitive load through a worked promotional-email example.
Examples
Uses promotional-email code, descriptive collection names, boolean naming, domain terms, and familiar loop-variable exceptions.
What you can do after
Apply naming and scope decisions that make intent visible and keep the main logic easy to follow.
How it connects
Connects variable naming with scope, collections, booleans, lambdas, domain vocabulary, method names, and cognitive load.

Also explained in

Compare how 3 books explain variable naming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.