开发者

Best way to format the conditional checks in "if" statement

开发者 https://www.devze.com 2023-03-31 11:02 出处:网络
This code looks di开发者_开发知识库rty and I can\'t figure out how to format it so that I can read it, understand it, and look clean at the same time.

This code looks di开发者_开发知识库rty and I can't figure out how to format it so that I can read it, understand it, and look clean at the same time.

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

Any suggestions?


I would break down the boolean expressions into variables named for readability. Something like:

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);
}


Consider refactoring. You could put sub expressions into their own functions, thus naming their purpose.

For example:

if (IsCentered(center) && IsInsideLower(y, j, i) && IsInsideUpper(y, j, i))
  regenerateDot(i + 1, j, dots);

Note that in the above example the function names might be bogus (I haven't really attempted to understand what the purpose of the code is), but you should get the picture.


Almost all the parenthesis are redundant... and adding some whitespace it becomes:

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


For something complicated I'd probably break it down into what each condition (grouped by shared &&) is trying to signify and assign it to a sensible variable name.


At most you can remove extra braces, add some spaces and put the logical partitions in different lines as,

if(center == 2 && 
  (((y - height/2) == j || (y + height/2) == j) && (x + width/2) == i))
{
  regenerateDot(i+1, j, dots);
}

Edit: You have one redundant condition (x + width/2) == i which I have optimized here.


This is the same as the code you posted:

if( center == 2 )
{
    if( (x+width/2) == i )
    {
        if( (y-height/2) == j ) || (y+height/2) == j ) )
        {
            regenerateDot(i+1, j, dots); 
        }
    }
}


Re-ordering it would give something like :

if (center==2 && (i-x)==(width/2) && abs(j-y)==(height/2))
    regenerateDot(i+1, j, dots); 


I would do it like this

if (2 == center &&  
    (((y - height/2) == j && (x + width/2) == i) ||  
     ((y + height/2) == j && (x + width/2) == i))
   )
{ 
  regenerateDot(i + 1, j, dots); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消