Skip to Content
先整理?
book

先整理?

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

第 1 章. 守护条款

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

你会看到这样的代码

if (condition)
    ...some code...

或者这样更好:

if (condition)
    if (not other condition)
        ...some code...

作为读者,很容易在嵌套条件中迷失。将上述内容Tidy到:

if (not condition) return
if (other condition) return
...some code...

这样更容易读懂。它说:"在了解代码的细节之前,我们需要牢记一些先决条件"。

(但是,MuLTipLe ReTuRns 呢?例程只有一个返回点的 "规则 "来自 FORTRAN 时代,当时一个例程可以有多个入口出口点。要调试这样的代码几乎是不可能的。你无法知道执行了哪些语句。带有保护子句的代码更容易分析,因为前提条件是明确的)。

不要过多使用保护分句。一个例程中包含七八个守护子句(我曾亲眼见过),阅读起来并不轻松。它需要更多的关注来划分复杂性。

只有在精确满足提示的情况下,才对保护子句进行整理:

if (condition)
    ...all the rest of the code in the routine...

我看到想整理却整理不了的代码:

if (condition)
    ...some code...
...some other code...

也许前两行可以提取到一个辅助方法中,然后再整理一个守护子句,但始终只能采取微小的步骤。

下面是一个例子:https://github.com/Bogdanp/dramatiq/pull/470。

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