Quantcast
Channel: Анал со зрелой
Viewing all articles
Browse latest Browse all 47

Good If Statements – Self Documenting Code

$
0
0

Here’s a quick trick for documenting those pesky if-statements, especially when littered with complicated mathematics.

Here’s an example from Timothy Master’s “Pragmatic Neural Network Recipes in C++” where the author needed to test some interval bounds to see if the conditions were appropriate to perform a parabolic estimate of a step-size. Sounds, and looks, complicated:

if ((fabs(step) < fabs(0.5 * testdist))     // If shrinking
	&& (step + xbest > xlow)            // and within known bounds
	&& (step + xbest < xhigh)) {        // then we can use the
	xrecent = xbest + step;             // parabolic estimate
	if ((xrecent - xlow < tol2) ||      // If we are very close
		(xhigh - xrecent < tol2)) { // to known bounds
		if (xbest < xmid)           // then stabilize
			step = tol1;
		else
			step = -tol1;
	}
}

In my opinion this author writes extremely good code. In the above example the details of the code are very well documented, however that’s just due to wonderful (albeit dubiously placed) comments. When modified slightly the code can still maintain the same readability and perhaps gain a little clarity:

int shrinking = abs( step ) < abs( 0.5f * testdist );
int boundLow = step + xbest > xlow;
int boundHigh = step + xbest < xhigh;

// parabolic estimate
if ( shrinking && boundLow && boundHigh )
{
	float xrecent = xbest + step;
	int closeToKnownBounds = (xrecent - xlow < tol2) || (xhigh - xrecent < tol2);

	if ( closeToKnownBounds )
	{
		// stabalize
		if ( xbest < xmid )
		{
			step = tol1;
		}

		else
		{
			step = -tol1;
		}
	}
}

The trick is to just name those little integer values that collapse down to a 1 or 0 (the comparison operators in C, like && and ||, take their arguments and return a 1 or 0). One of the most common applications of this kind of naming is when there’s a complex end condition in an algorithm. Often times this kind of termination criterion can just be called “done”:

int IterativeAlgorithm( )
{
	params = initialize( );

	while ( 1 )
	{
		float error = EstimateError( );
		
		// ... work is done here
		
		// random example of a complex predicate
		int converged = x0 * x1 < relTol * error + absTol;
		
		if ( converged )
		{
			return 1;
		}
		
		else
		{
			int diverged = ComplexPredicate( );
			
			if ( diverged )
			{
				return 0;
			}

			// setup next iteration ...
		}
	}
}

 

TwitterRedditFacebookShare


Viewing all articles
Browse latest Browse all 47

Trending Articles