Skip to Content
先整理?
book

先整理?

by Kent Beck
May 2025
Intermediate to advanced
124 pages
1h 7m
Chinese
O'Reilly Media, Inc.
Content preview from 先整理?

第 7 章 将声明和初始化放在一起 将声明和初始化移到一起

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

变量和变量的初始化有时似乎相去甚远。变量的名称会提示 变量在计算中的作用。然而,初始化会强化名称所传达的信息。当你遇到将声明(可能的类型)和初始化分开的代码时,阅读起来就比较困难了。当你读到初始化时,你已经忘记了变量的一些作用

下面就是这种 Tidy 的样子。想象一下,你有这样一些代码

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 将初始化移到声明中:

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

调整顺序。如果每个变量都在使用前声明并初始化,还是在函数顶部一起声明并初始化更容易阅读和理解代码?这时,你就可以成为一名悬疑作家,想象代码读者的阅读体验,给他们留下猜测代码作者的线索。

变量和设置变量的代码不能随意排列。必须尊重变量之间的数据依赖关系。如果使用a 来初始化b ,就必须先初始化a 。在执行 Tidy 时,请记住必须保持数据依赖关系的顺序。

如果你必须手工分析数据 依赖关系,你最终还是会犯错误。当你只是想改进代码结构时,却不小心改变了代码的行为。没问题,备份到已知正确的代码版本。小步快跑,这就是 Tidy 的工作方式。大的设计变更太难太可怕?那就小步快跑。不,是更小。还怕吗?不害怕?很好。

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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

超越Vibe编程

超越Vibe编程

Addy Osmani
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉

Publisher Resources

ISBN: 9798341656949