Labels found useful for Native C++ Development


Using labels in modern programming is often considered a bad practice, as it results in spaghetti (unmaintainable) code. However, I often find it very useful for native C/C++ programming, where no exceptions are used (error handling using return values is extensively used) and memory management is needed.It increases the readability and maintainability of the code to a great extent.

The following code does not utilize a label, it has :

1- A lot of Nested If Loops, causing bad readability.

2- Redundant memory cleaning code, causing bad maintainability.

DWORD Foo_NoLabel() {

DWORD    dwErr = NO_ERROR;
Boo      *pBoo = NULL;
Soo      *pSoo= NULL;
Doo      *pDoo= NULL;
Loo      *pLoo= NULL;

dwErr = GetBoo(&pBoo);
if (dwErr == NO_ERROR)  {
    dwErr = GetSoo(&pSoo);
    if (dwErr == NO_ERROR) {
        dwErr = GetDoo(&pDoo);
        if (dwErr == NO_ERROR) {
            dwErr = GetLoo(&pLoo);
            if (dwErr == NO_ERROR) {
                //Great!
            }
            else {
                //Oops!
                delete pBoo;
                delete pSoo;
                delete pDoo;
            }
        }
        else {
            //Oops!
            delete pBoo;
            delete pSoo;
        }
     }
    else {
        //Oops!
        delete pBoo;
     }
}

if (dwErr == NO_ERROR) {
    dwErr = UseAll(pBoo,pLoo,pDoo,pSoo);

    delete pBoo;
    delete pSoo;
    delete pDoo;
    delete pLoo;
}

return dwErr;

}

This much cleaner code uses a CleanUp label:


DWORD Foo_UsingLabel() {

DWORD    dwErr = NO_ERROR;
Boo      *pBoo = NULL;
Soo      *pSoo= NULL;
Doo      *pDoo= NULL;
Loo      *pLoo= NULL;

dwErr = GetBoo(&pBoo);
if (dwErr != NO_ERROR)  { goto CleanUp;}

dwErr = GetSoo(&pSoo);
if (dwErr != NO_ERROR)  { goto CleanUp;}

dwErr = GetDoo(&pDoo);
if (dwErr != NO_ERROR)  { goto CleanUp;}

dwErr = GetLoo(&pLoo);
if (dwErr != NO_ERROR)  { goto CleanUp;}

dwErr = UseAll(pBoo,pLoo,pDoo,pSoo);

CleanUp:
if (pBoo) delete pBoo;
if (pSoo) delete pSoo;
if (pDoo) delete pDoo;
if (pLoo) delete pLoo;

return dwErr;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s