前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.2: 适当的抽象好于直接使用语言功能

C++核心准则ES.2: 适当的抽象好于直接使用语言功能

作者头像
面向对象思考
发布2020-04-17 17:32:29
3250
发布2020-04-17 17:32:29
举报
ES.2: Prefer suitable abstractions to direct use of language features

ES.2: 适当的抽象好于直接使用语言功能

Reason(原因)

A "suitable abstraction" (e.g., library or class) is closer to the application concepts than the bare language, leads to shorter and clearer code, and is likely to be better tested.

“适当的抽象”(例如库或类)比直接使用语言功能更接近应用概念,这会带来更短、更清晰的代码,很有可能被更好地测试。

Example(示例)

代码语言:javascript
复制
vector<string> read1(istream& is)   // good
{
    vector<string> res;
    for (string s; is >> s;)
        res.push_back(s);
    return res;
}

The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:

更加传统的、低层次的差不多等价的代码会更长,更乱,更难保证正确性,而且很有可能更慢。

代码语言:javascript
复制
char** read2(istream& is, int maxelem, int maxstring, int* nread)   // bad: verbose and incomplete
{
    auto res = new char*[maxelem];
    int elemcount = 0;
    while (is && elemcount < maxelem) {
        auto s = new char[maxstring];
        is.read(s, maxstring);
        res[elemcount++] = s;
    }
    nread = &elemcount;
    return res;
}

Once the checking for overflow and error handling has been added that code gets quite messy, and there is the problem remembering to delete the returned pointer and the C-style strings that array contains.

一旦增加了溢出检查,错误处理,代码会变得很乱,而且还存在需要记住销毁返回的指针和数组包含的C风格字符串的问题。

Enforcement(实施建议)

Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?

不容易,不容易。寻找混乱的循环、嵌套循环、长函数、函数调用缺失、很少被使用的内置类型?还是确认圈复杂度?

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es2-prefer-suitable-abstractions-to-direct-use-of-language-features

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档