C Sharp

Improving Code Readability

When using exception-handling code, code readability improves enormously. This directly relates to reduced costs in terms of code maintenance. The way in which return codes are handled vs. the exception-handling syntax is the source of this improvement. If you used return codes with the AccessDatabase.GenerateDatbase method mentioned previously, code similar to the following would be required to handle error conditions: -

public bool GenerateDatabase()
{
    if (CreatePhysicalDatabase())
    {
        if (CreateTables())
        {
            if (CreateIndexes())
            {
                return true;
            }
            else
            {
                // Handle error.
                return false;
            }
        }
        else
        {
            // Handle error.
            return false;
        }
    }
    else
    {
        // Handle error.
        return false;
    }
}

Add a few other validations to the preceding code and you wind up with a tremendous amount of error validation code mixed in with your business logic. If you indent your code 4 spaces per block, the first character of a line of code might not appear until column 20 or greater. None of this is disastrous for the code itself, but it does make the code more difficult to read and maintain, and the bottom line is that code that's difficult to maintain is a breeding ground for bugs. Let's look at how this same example would look if exception handling were used: -

// Calling code.
try
{
    AccessDatabase accessDb = new AccessDatabase();
    accessDb.GenerateDatabase();
}
catch(Exception e)
{
    // Inspect caught exception.
}
// Definition of AccessDatabase.GenerateDatabase method.
public void GenerateDatabase()
{
    CreatePhysicalDatabase();
    CreateTables();
    CreateIndexes();
}

Notice how much cleaner and more elegant the second solution is. This is because error detection and recovery code are no longer mixed with the logic of the calling code itself. Because exception handling has made this code more straightforward, maintaining the code has been made much easier.