C++ 长函数调用的可读性
我一直在编写使用函数调用的代码,这些函数调用非常长,通常超过80个字符。通常我会像这样拆分这些函数调用:C++ 长函数调用的可读性,c++,readability,C++,Readability,我一直在编写使用函数调用的代码,这些函数调用非常长,通常超过80个字符。通常我会像这样拆分这些函数调用: LongFunctionName(first_argument, another_argument, finally_last_argument); 然而,当我尝试将其放入if语句时,它看起来很奇怪,主要是因为它不太清楚它与什么值进行比较: if(LongFunctionName(first_argument,
LongFunctionName(first_argument,
another_argument,
finally_last_argument);
然而,当我尝试将其放入if语句时,它看起来很奇怪,主要是因为它不太清楚它与什么值进行比较:
if(LongFunctionName(first_argument,
another_argument,
finally_last_argument) != value_compared_to)
{
// stuff to be called
}
<>你如何格式化该语句更可读,并适合80个字符? < P>我会考虑把函数调用放在自己的行:
const auto value = LongFunctionName(first_argument,
another_argument,
finally_last_argument);
if (value != value_compared_to) {
// ...
}
您甚至可以为值
变量指定一个很好的描述性名称,以帮助理解代码。您有两个选择:
(一)
接受它看起来是这样的
或
(二)
在单独的语句(伪代码)中计算函数调用的返回值
别让我们从那件事开始,我会的
if
( LongFunctionName
( first_argument
, another_argument
, finally_last_argument
) != value_compared_to
)
{
// stuff to be called
}
在我看来,将返回值存储在变量中是最好的解决方案。但您可以做其他事情:
if (value_compared_to != LongFunctionName(first_argument,
another_argument,
finally_last_argument))
自从“80个字符”的指导方针以来,屏幕已经变得更大了。@StoryTeller:但我们仍然必须经常在分屏模式下工作,如果不是总是这样的话。@StoryTeller我知道,但当我试图编写可以在项目之间共享的代码时,我尽量保持每行80个字符。@Haroogan,你们两人都举了一些例子,说明如何遵循所使用的工具,而不是获得更好的工具。@StoryTeller:在拆分屏幕中工作与工具有什么关系?没错。现在,在调试时,您可以看到函数的结果或在其上设置断点。嵌套函数非常糟糕。这看起来是最好的方法。我想到了它,但它似乎只会使函数更大,因为将分配另一个变量。然而,当我想到@SteveWellens所说的调试时,它甚至可能会变得有用。即使没有名称,该区域仍然需要存在于内存中。谢谢。:-)不,不,不。它看起来更像是一些围绕标点符号的跳跃词,而不是逻辑代码。我认为这样的代码很难维护。
if (value_compared_to != LongFunctionName(first_argument,
another_argument,
finally_last_argument))