Skip to Content
Tidy First?
book

Tidy First?

by Kent Beck
October 2023
Intermediate to advanced
122 pages
1h 58m
English
O'Reilly Media, Inc.
Book available
Content preview from Tidy First?

Chapter 7. Move Declaration and Initialization Together

Variables and their initialization seem to drift apart sometimes. The name of a variable gives you a hint as to its role in the computation. However, the initialization reinforces the message of the name. When you come across code that separates the declaration (with a possible type) and initialization, it’s harder to read. By the time you get to the initialization, you’ve forgotten some of the context of what the variable is for.

Here’s what this tidying looks like. Imagine you have some code like this:

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. Is it easier to read and understand the code if each of the variables is declared and initialized just before it’s used, or if they’re all declared and initialized together at the top of the function? This is where you get to be a mystery writer, imagining the experience of a reader of your code and leaving them the clues they need to guess who done it.

You can’t just put variables and code that sets them in any old order. You must respect the data dependencies between variables. If you use a to initialize b, you have to initialize a first. As you’re ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Building Micro-Frontends

Building Micro-Frontends

Luca Mezzalira
Learning Go

Learning Go

Jon Bodner
Head First Git

Head First Git

Raju Gandhi

Publisher Resources

ISBN: 9781098151232Errata Page