在《The Pragmatic Programmer: From Journeyman to Master》(中文译名为《程序员修炼之道--从小工到专家》)Tip25 “怎样配平资源“中有一个重构代码的经典案例,现转录如下:
提示35
Finish What You Start
要有始有终
在大多数情况下这条提示都很容易应用。它只是意味着,分配某项资源的例程或对象应该负责解除该资源的分配。让我们通过一个糟糕的代码例子来看一看该提示的应用方式——这是一个打开文件、从中读取消费者信息、更新某个字段、然后写回结果的应用。我们去除了其中的错误处理代码,以让例子更清晰:
void readCustormer(const char *fName, Customer *cRec) {
cFile = fopen(fName, "r+");
fread(cRec, sizeof(*cRec), 1, cFile);
}
void writeCustomer(Customer *cRect) {
rewind(cFile);
fwrite (cRec, sizeof(*cRec), 1, cFile);
fclose(cFile);
}
void updateCustomer(const char *fName, double newBalance) {
Customer cRec;
readCustomer (fName, &CRec);
cRec.balance = newBalance;
writeCustomer(&cRec);
}