在"if"语句中格式化条件检查的最佳方法

Lig*_*uzz 8 c++ code-formatting

这段代码看起来很脏,我无法弄清楚如何格式化它,以便我可以阅读,理解它,同时看起来干净.

if(center==2 && ((((y-height/2)==j) && ((x+width/2)==i)) || (((y+height/2)==j) &&  ((x+width/2)==i))))
  regenerateDot(i+1, j, dots); 
Run Code Online (Sandbox Code Playgroud)

有什么建议?

cdm*_*kay 17

我会将布尔表达式分解为以可读性命名的变量.就像是:

bool isCentered = center == 2;
bool inLowerRegion = (y-height/2) == j && (x+width/2) == i;
bool inUpperRegion = (y+height/2) == j && (x+width/2) == i;
bool inEitherRegion = inLowerRegion || inUpperRegion;

if (isCentered && inEitherRegion) {
   regenerateDot(i+1, j, dots);
}
Run Code Online (Sandbox Code Playgroud)

  • @iammilind:额外的括号很好,我会把它们拿出来.'inEitherRegion`额外变量是一个品味问题.对我而言,它使`if`更具可读性. (2认同)
  • 我肯定会考虑使用函数而不是局部变量.它们增加了主要的功能长度并引入了新的变量来跟踪(大脑过载). (2认同)

Chr*_*n.K 6

考虑重构.您可以将子表达式放入它们自己的函数中,从而命名它们的用途.

例如:

if (IsCentered(center) && IsInsideLower(y, j, i) && IsInsideUpper(y, j, i))
  regenerateDot(i + 1, j, dots);
Run Code Online (Sandbox Code Playgroud)

请注意,在上面的示例中,函数名称可能是伪造的(我还没有真正试图理解代码的用途是什么),但是你应该得到图片.