
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
第1章 卫述句
你常常会看到这样的代码:

或者稍好一点的:

代码阅读者很容易被嵌套条件搞晕。要像这样整理上面的代码:

这样更容易读懂。它的意思是:“在深入代码的细节之前,需要处理一些前提条件”。但是,多条返回语句是怎么回事呢?一个例程(routine)只有一条返回语句的“规则”来自FORTRAN时代,那时一个例程可以有多个入口点和出口点。你几乎无法调试这样的代码,也不知道执行了哪些语句。使用卫述句的代码则更容易分析,因为前提条件是明确的。
不要过多使用卫述句。一个包含七八条卫述句的例程读起来也并不轻松,往往需要我们投入更多的精力。
只有在精确匹配以下情形时,才能整理成卫述句:

像下面这样的代码则很难整理:

也许可以将前两行提取到一个辅助函数中,然后再将之整理成卫述句,但要始终采取小步的方式。
下面是一个例子:https://github.com/Bogdanp/dramatiq/pull/470。