Friday, September 22, 2006

And I, I Took the Return Path Less Traveled By

And that has made all the difference.

When you get into the mind-set that multiple return-paths are ok you run risks.

Pre-Conditions are usually ok, and not a horrible idea, unless implemented part-way through the function.

When you get into the mind-set that multiple return-paths are ok, you run the risk of writing (and possibly maintaining) code that does the following. And if you're especially unlucky, (like the original programmer) your code is being used in a Windows service where people expect things to run for months between restarts.

bool TSomeClass::SomeFunction()
{
long RECORD_ID = GetRecordID();

if( RECORD_ID )
{
THandlerClass *Handler = new THandlerClass();

Handler->LoadRecord( RECORD_ID );

if( Handler->SomeBoolFlag == false )
{
ReportError( "Some Bool Flag is false - can't continue" );
return false;
}

Handler->Process();

delete Handler;

return true;
}
else
{
ReportError( "Record ID is not set - unable to process." );
}

return false;
}



Moral of the story?

Pre-Conditions should be before any memory allocation.

Also, if possible, create the memory in the constructor of a class and destroy it in the destructor - this way you don't have to worry about leaking memory inside functions, and unless you have a situation I ran into the other day where the destructor wasn't being called (the subject of a future posting) the memory will be released when the host object is destroyed.

0 Comments:

Post a Comment

<< Home