C++核心准则编译边学-F.3 保持函数简短
F.3: Keep functions short and simple(保持函数简短)
Reason(原因)
Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes. Functions with complex control structures are more likely to be long and more likely to hide logical errors
大的函数难于理解,更有可能包含复杂代码,还有可能包含超过最小作用域的变量。包含复杂控制结构的代码更有可能是长代码而且更容易隐藏逻辑错误。
Example(示例)
Consider(考虑如下代码):
double simple_func(double val, int flag1, int flag2)
// simple_func: takes a value and calculates the expected ASIC output,
// given the two mode flags.
{
double intermediate;
if (flag1 > 0) {
intermediate = func1(val);
if (flag2 % 2)
intermediate = sqrt(intermediate);
}
else if (flag1 == -1) {
intermediate = func1(-val);
if (flag2 % 2)
intermediate = sqrt(-intermediate);
flag1 = -flag1;
}
if (abs(flag2) > 10) {
intermediate = func2(intermediate);
}
switch (flag2 / 10) {
case 1: if (flag1 == -1) return finalize(intermediate, 1.171);
break;
case 2: return finalize(intermediate, 13.1);
default: break;
}
return finalize(intermediate, 0.);
}
This is too complex. How would you know if all possible alternatives have been correctly handled? Yes, it breaks other rules also.
We can refactor:
代码过于复杂。你怎么知道是否所有可能的分支都已经被正确处理了?是的,它也违反了其他的规则。
我们可以重构这段代码:
double func1_muon(double val, int flag)
{
// ???
}
double func1_tau(double val, int flag1, int flag2)
{
// ???
}
double simple_func(double val, int flag1, int flag2)
// simple_func: takes a value and calculates the expected ASIC output,
// given the two mode flags.
{
if (flag1 > 0)
return func1_muon(val, flag2);
if (flag1 == -1)
// handled by func1_tau: flag1 = -flag1;
return func1_tau(-val, flag1, flag2);
return 0.;
}
Note(注意)
"It doesn't fit on a screen" is often a good practical definition of "far too large." One-to-five-line functions should be considered normal.
“一屏显示不下”通常是一个定义“过大”代码的良好实践。一到五行的代码应该被认为是正常的。
Note(注意)
Break large functions up into smaller cohesive and named functions. Small simple functions are easily inlined where the cost of a function call is significant.
将大函数差分为较小的内聚函数并命名。当函数调用代价过大时简短的函数容易linline化。
译者注:不需要过于担心因为函数简短而增加的调用代价。
Enforcement(实施建议)
Flag functions that do not "fit on a screen." How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
标记“一屏装不下”的函数。一屏是多大?试试60行80列。这大概是令人舒适的一页书的最大值。
Flag functions that are too complex. How complex is too complex? You could use cyclomatic complexity. Try "more than 10 logical path through." Count a simple switch as one path.
标记过于复杂的函数。多复杂算过于复杂?你可以使用圈复杂度。尝试标记超过10条逻辑路径的情况。简单的switch语句算作1条路径。