找回密码
 立即注册
  • QQ空间
  • 回复
  • 收藏

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

admin 2019-10-8 18:51 110人围观 C++相关



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 librariesdesigned 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.

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



      ----------------------------------------------------------------------------------------------------------------------
      我们尊重原创,也注重分享,文章来源于微信公众号:面向对象思考,建议关注公众号查看原文。如若侵权请联系qter@qter.org。
      ----------------------------------------------------------------------------------------------------------------------

      鲜花

      握手

      雷人

      路过

      鸡蛋

      yafeilinux和他的朋友们微信公众号二维码

      微信公众号

      专注于Qt嵌入式Linux开发等。扫一扫立即关注。

      Qt开源社区官方QQ群二维码

      QQ交流群

      欢迎加入QQ群大家庭,一起讨论学习!

      我有话说......