适当的抽象好于直接使用语言功能

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(示例)

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:

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

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?

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

本页共38段,1637个字符,2171 Byte(字节)