Stop Reassigning Variables!

When writing code, especially in dynamic languages like Python, it’s tempting to reuse and reassign a variable multiple times. We should be advocating for a powerful practice that significantly improves code quality: Single Assignment.

The rule is simple, echoing the advice of software veterans like John Carmack: Strive to assign a value to a variable only once outside of true iterative calculations (like accumulation inside a loop).


🎯 Why Single Assignment is Fundamentally Better

1. Eliminates Temporal Coupling πŸ•°οΈ

When you reassign a variable (x = 7, then x = x + 3), you create an implicit ordering dependency known as temporal coupling. Later code blocks rely on the variable being in a specific, mutated state.

  • Problem: If you move or refactor a block of code, it might silently use an outdated or incorrect version of the variable, leading to hard-to-find bugs because the implicit order has been broken.
  • Solution: Single assignment forces you to use unique variable names for each intermediate step (x1 = 7, then x2 = x1 + 3), making all dependencies explicit and preventing hidden state errors.

2. Enables Easier Debugging and Local Reasoning πŸ•΅οΈ

Immutability ensures your code supports better inspection and testing:

  • Debugger Clarity: By keeping all intermediate calculation results available under unique names, debugging becomes significantly simpler. You never lose the original or the state from a prior step.
  • Pure Functions: Immutability supports the use of pure functions (functions without side effects). This allows you to treat every function as a “black box”: it only needs to know the data passed in, and it cannot be changed by anything outside. This dramatically improves testability and local context.

3. Aligns with Best Practices πŸ”’

The principle that variables should not change is so critical that many robust languages default to it:

  • In C/C++, making almost every variable const at initialization is widely considered good practice.
  • In languages like Rust or Swift, the compiler will often warn you to make a variable immutable if you never mutate it, pushing developers toward the single assignment default.

πŸ›‘ Where to Avoid Reassignment (The Conditional Pitfall)

The most common place for unnecessary reassignment is when initializing a variable before conditional logic (if/else).

❌ The Code to Avoid (Double Assignment):

Here, a is assigned twice: once with None, and potentially a second time inside the if block.

a = None # Assignment 1
if foo:
  a = bar() # Assignment 2 (Conditional Reassignment)

βœ… The Better Way (Single Assignment):

This pattern ensures that a is assigned its final, correct value only once within its execution path, eliminating the possibility of accidentally using an uninitialized or stale default value later.

if foo:
  a = bar()
else:
  a = None # a is assigned only once, regardless of the condition

Happy coding!