OdeToCode IC Logo

Error Handling

Friday, February 4, 2005

When looking at the code for a product or library, I find I’m always drawn to look at the error handling and validation pieces. Since every piece of software has these pieces in one form or another it’s always interesting to compare and contrast the different practices and methodologies used throughout the industry. The newly released Enterprise Library, being from the patterns and practices group, obviously had some thought put into this area, so I was keenly interested to peek at the code.

Here is one of the constructors from the Enterprise Library’s ConfigurationBuilder class:

   66 public ConfigurationBuilder(string configurationFile)

   67 {

   68    ArgumentValidation.CheckForNullReference(configurationFile, "configurationFile");

   69    ArgumentValidation.CheckForEmptyString(configurationFile, "configurationFile");

   70 

   71    LoadMetaConfiguration(configurationFile);

   72 }

The code snippet is short, but tells a tale. It tells me I can expect the Enterprise Library to validate explicitly all the parameters I pass.

The code snippet also tells me the team made a decision to let constructors throw exceptions. Deciding to let exceptions escape from a constructor is not an easy decision, particularly in this case because the ConfigurationBuilder class inherits from IDisposable. If the constructor acquires a resource (say, opens a configuration file) and then throws - there is no object reference returned by the constructor for the client to invoke Dispose upon.

On the other hand, covering this edge condition always increases the complexity of the internal implementation, and can also make the public interface harder to use (for instance if the client has to invoke both a constructor and an Initialize method).

It's a tough tradeoff - 'simple elegance' or 'paranoid error handling'. Which do you prefer?