👨‍💻
Software Engineering
Tidy First?: A Personal Exercise in Empirical Software Design
Tidy First?: A Personal Exercise in Empirical Software Design
  • Tidy First?
  • Foreword
  • Preface
  • Part 1: Tidyings
    • 1: Guard Clauses
    • 2: Dead Code
    • 3: Normalize Symmetries
    • 4: New Interface, Old Implementation
    • 5: Reading Order
    • 6: Cohesion Order
    • 7: Move Declaration & Initialization Together
    • 8: Explaining Variables
    • 9: Explaining Constants
    • 10: Explicit Parameters
    • 11: Chunk Statements
    • 12: Extract Helper
    • 13: One Pile
    • 14: Explaining Comments
    • 15: Delete Redundant Comments
  • Part 2: Managing
    • Coming soon
  • Part 3: Theory
    • Coming soon
Powered by GitBook
On this page
  1. Part 1: Tidyings

7: Move Declaration & Initialization Together

Sometimes variable initialization and declaration drift apart.

While a variable's name gives a hint of its role, the initialization reinforces the message of the name.

Code that separates declaration from initialization makes it harder to read. By the time you get to the initialization, some of the context has been forgotten.

Example:

fn()
    int a
    ...some code that doesn't use a
    a = ...
    int b
    ...some more code, maybe it uses a but doesn't use b.
    b = ...a...
    ...some code that uses b

Tidy this by moving the initialization up to the declaration

fn()
    int a = ...
    ...some code that doesn't use a
    ...some more code, maybe it uses a but doesn't use b
    int b = ...a...
    ...some code that uses b

Play around with the order.

It is easier to read and understand the code if each of the variables is declared and initialized just before it's used? Or, is it better if they're all declared and initialized at the top of the function? Imagine the experience for the next reader.

We need maintain the order of dependencies with respect to variable initialization.

Work in small steps That's the tidying way. Big design changes too hard & scary? Take smaller steps.

Previous6: Cohesion OrderNext8: Explaining Variables

Last updated 10 days ago