Course contentsShow
← Software Engineering
Lesson 370 of 1,93311. Code Quality and ReadabilityFree lesson

Variable Scope and Name Length

Balancing name verbosity with scope: shorter names for narrow scopes, longer descriptive names for wider visibility.

Variable Scope and Name Length

You'll learn: How to choose variable name length based on how widely the variable is used in your code.

The Core Principle

Not all variables need equally descriptive names. The visibility and lifetime of a variable should guide how verbose its name is:

  • Narrow scope (a few lines): Short names like i, x, or temp are fine
  • Wide scope (across methods or classes): Longer, descriptive names like customerAccountBalance are essential

Think of it like addressing people: you might say "Hey, you!" to someone standing right next to you, but you'd use their full name when talking about them to someone across the room who can't see them.

Why This Matters

When a variable exists for just 3-5 lines in a loop, its context is immediately visible. A reader can glance up and understand what i means. But when a variable travels across methods or lives as a class field, readers encounter it far from its declaration. Without a descriptive name, they're lost.

# Narrow scope - short name is fine
for i in range(10):
    print(i * 2)

# Wide scope - needs description
class ShoppingCart:
    def __init__(self):
        self.totalPriceIncludingTax = 0  # Used across many methods

The Balance

Over-describing narrow-scope variables wastes reading time. Under-describing wide-scope variables forces readers to hunt for context. Match name length to scope size.

Key Takeaway: Short names work in tight scopes where context is obvious; longer, descriptive names are essential for variables with wider visibility or longer lifetimes.