Wednesday, June 4, 2008

Parse TryParse Code Pattern

In c# the int data type has two functions for parsing strings that represent integers; Parse and TryParse.

Parse can throw an exception to indicate failure and TryParse returns a bool to indicate success or failure.

This represents a useful Code Pattern that frameworks can employ to address the needs of those who use them. On the one hand throwing an exception is the traditional way that frameworks indicate something went wrong. It leaves it up to the calling entity to catch and handle the exceptions. The weakness here is that the catching and handling structure can be overwhelming. Not to mention the overhead involved.

The TryParse on the other hand allows the calling entity to branch on success or failure without exception overhead. It also allows for several quick successive checks of parsing to find the best fit.

Neither is superior, it is simply a case of what is needed. So in creating frameworks it is best to provide both.

No comments: