Monday, July 12, 2010

Refactoring with References and Pointers Tip

Inherited source code is a fact of life for any professional programmer.  Sometimes you inherit a 5000+ line C++ method chock full of pointers and pointers to pointers.

If you’re utilizing the copy-and-paste algorithm for refactoring large blocks of pointer and pointer-to-pointer riddled code then C++’s Pass by Reference support can make these changes much less painful.  Thankfully it supports References to Pointers!

So instead of taking a block similar to the following:

int *ptr = NULL;

if ( someCond )
ptr = new int[len]; // we either allocate it here or leave it null

for (int i=0; i < len; i++)
{
if ( ptr == NULL )
{
ptr = new int[len];
}
else
{
delete [] ptr;
ptr = new int[len + i];
}

int x = ptr[i] * ptr[i + 1];
// ... several hundred lines of code
}






and converting the loop into something unreadable, error prone and barely recognizable as the former loop body:




void SomeFunc(int** ptr, int len)
{
for (int i=0; i < len; i++)
{
if ( (*ptr) == NULL )
(*ptr) = new int[len];
else
{
delete [] (*ptr);
(*ptr) = new int[len + i];
}

int x = (*ptr)[i] * (*ptr)[i + 1];
// ... several hundred lines of code
}
}





You can convert the loop into something easily recognizable as the former loop ala:




void SomeFunc(int*& ptr, int len)
{
for (int i=0; i < len; i++)
{
if ( ptr == NULL )
{
ptr = new int[len];
}
else
{
delete [] ptr;
ptr = new int[len + i];
}

int x = ptr[i] * ptr[i + 1];
}
}



No comments :

Post a Comment