Best way to format conditional checks in an if statement

This code looks dirty and I can't figure out how to format it so that I can read it, understand it and at the same time look clean.

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?

+8
c ++ code-formatting
source share
8 answers

I would break logical 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); } 
+17
source share

Consider refactoring. You can put subexpressions into your own functions, thereby naming your goal.

For example:

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

Note that in the above example, function names may be fictitious (I didn't really try to figure out what the purpose of the code is), but you should get an image.

+6
source share

In most cases, you can remove the extra curly braces, add spaces and put logical partitions on different lines, like

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

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

+2
source share

For something complicated, I would probably divide it into the fact that each condition (grouped by shared & &) tries to denote and assign it to a reasonable variable name.

+2
source share

Almost all brackets are redundant ... and adding some spaces 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); 
+1
source share

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); } 
+1
source share

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); } } } 
+1
source share

Reordering will produce the following:

 if (center==2 && (ix)==(width/2) && abs(jy)==(height/2)) regenerateDot(i+1, j, dots); 
+1
source share

All Articles