C++核心准则边译边学-P.11 封装混乱的代码,而不是传播它们​

C++ 专栏收录该内容
561 篇文章 19 订阅

P.11: Encapsulate messy constructs, rather than spreading through the code 封装混乱的代码,而不是传播它们

Reason(原因)

Messy code is more likely to hide bugs and harder to write. A good interface is easier and safer to use. Messy, low-level code breeds more such code.

混乱的代码很容易隐藏错误并且很难编写。一个好的接口会易用且安全。混乱的,低层次代码会产生很多像下面示例一样的程序。

Example(示例)

 

int sz = 100;int* p = (int*) malloc(sizeof(int) * sz);int count = 0;// ...for (;;) {    // ... read an int into x, exit loop if end of file is reached ...    // ... check that x is valid ...    if (count == sz)        p = (int*) realloc(p, sizeof(int) * sz * 2);    p[count++] = x;    // ...}

This is low-level, verbose, and error-prone. For example, we "forgot" to test for memory exhaustion. Instead, we could use vector:

这是一段低层次,冗长,易错的代码。例如,我们忘记了检查内存枯竭。作为代替手段,我们可以使用vector:

 

vector<int> v;v.reserve(100);// ...for (int x; cin >> x; ) {    // ... check that x is valid ...    v.push_back(x);}

译者注:vector在保证高性能的前提下,还可以提供完善的内存管理。

 

Note(注意)

The standards library and the GSL are examples of this philosophy. For example, instead of messing with the arrays, unions, cast, tricky lifetime issues, gsl::owner, etc., that are needed to implement key abstractions, such as vector, span, lock_guard, and future, we use the libraries designed and implemented by people with more time and expertise than we usually have. Similarly, we can and should design and implement more specialized libraries, rather than leaving the users (often ourselves) with the challenge of repeatedly getting low-level code well. This is a variant of the subset of superset principle that underlies these guidelines.

标准库和GSL可以作为这个原则的范例。例如,与其直接使用数组、联合体、类型转换,自己处理生命周期、gsl::owner等问题,不如使用标准库提供的vector,span,lock_guard和future等经过经过更高层次抽象和实现的功能。标准库的设计和开发者和我们相比,时间更充裕,经验也更丰富。类似的,我们可以也应该设计和实现专用库,而不是让使用者(通常是我们自己)自己不断地挑战低层次代码。这是构成本准则中部分原则的另一种说法。

Enforcement(实施建议)

  • Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.

        找到“混乱代码”,例如复杂指针操作或者除了实现抽象之外的类型转换。

 

觉得本文有帮助,欢迎点赞并分享给更多的朋友!

阅读更多更新文章,请关注微信公众号【面向对象思考】

 

  • 2
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值