Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to format the conditional checks in "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 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?

like image 702
Lightyear Buzz Avatar asked Aug 30 '11 05:08

Lightyear Buzz


2 Answers

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.

like image 23
Christian.K Avatar answered Nov 05 '22 22:11

Christian.K


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);
}
like image 82
cdmckay Avatar answered Nov 05 '22 22:11

cdmckay