"Package" meaningful operations as carefully named functions - 提取一些常用的代码变成函数是非常有意义的

Reason

Factoring out common code makes code more readable, more likely to be reused, and limit errors from complex code. If something is a well-specified action, separate it out from its surrounding code and give it a name.

理由

提取一些公共的代码使得其变的更易读,那会让代码变得更加可用,并且减少错误。如果某些行为已经明确定义好了,那就单独把它隔离出来,并起一个名字。

错误方式

1 void read_and_print(istream& is)    // read and print an int
2 {
3     int x;
4     if (is >> x)
5         cout << "the int is " << x << '\n';
6     else
7         cerr << "no int on input\n";
8 }

Almost everything is wrong with read_and_print. It reads, it writes (to a fixed ostream), it writes error messages (to a fixed ostream), it handles only ints. There is nothing to reuse, logically separate operations are intermingled and local variables are in scope after the end of their logical use. For a tiny example, this looks OK, but if the input operation, the output operation, and the error handling had been more complicated the tangled mess could become hard to understand.

几乎所有的 read_and_print 都使用错了。

基本流程是这样的,首先read,然后write(向固定ostream写入),error信息也是一样(向固定ostream写入),问题是它只处理int类型数据。没有什么可重用的,逻辑上独立的操作被混合在一起,局部变量在其逻辑使用结束后仍在作用域中。错误处理变得更加复杂,混乱不堪,难以理解。

posted @ 2023-10-20 11:01  panda顾  阅读(8)  评论(0)    收藏  举报