F.2: A function should perform a single logical operation(一个函数只执行单一逻辑操作)

Reason(原因)

A function that performs a single operation is simpler to understand, test, and reuse.

执行单一操作的函数更容易理解,测试和复用。

Example(示例)

Consider(考虑下面的函数):

 

void read_and_print()    // bad{    int x;    cin >> x;    // check for errors    cout << x << "\n";}

This is a monolith that is tied to a specific input and will never find another (different) use. Instead, break functions up into suitable logical parts and parameterize:

这是一个绑定到特定输入的代码块,永远不会找到另一个(不同的)用途。我们可以将函数拆分成合适的逻辑块并参数化:


int read(istream& is)    // better{    int x;    is >> x;    // check for errors    return x;}
void print(ostream& os, int x){ os << x << "\n";}

These can now be combined where needed:

这些函数可以在需要的时候组合使用:


void read_and_print(){    auto x = read(cin);    print(cout, x);}

If there was a need, we could further templatize ​​read()​​​ and ​​print()​​ on the data type, the I/O mechanism, the response to errors, etc. Example:

如果有需要,我们可以针对数据类型,输入/输出机制,错误处理等模板化read()和print(),例如:


auto read = [](auto& input, auto& value)    // better{    input >> value;    // check for errors};
auto print(auto& output, const auto& value){ output << value << "\n";}

Enforcement(实施建议)

  • Consider functions with more than one "out" parameter suspicious. Use return values instead, including​​tuple​​ for multiple return values.
    怀疑具有多个输出参数的函数。改用返回值,如果多个返回值时可以使用tuple。
  • Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.
    怀疑超过一个编辑屏幕的巨大函数。考虑将这个函数重构为稍小的经过良好命名的子操作。
  • Consider functions with 7 or more parameters suspicious.
    怀疑包含7个(或以上)参数的函数。

 


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