How exceptionality and naming are linked

Each method should have a clear, simple purpose. The name of the method describes this cohesive meaning. Exceptions denote behavior that breaks the cohesion.

The naming of .NET Parse and TryParse methods illustrates how naming and exceptionality are linked via cohesion:

// Parse promises to *parse* and thus not being able to
// parse is exceptional.
try
{
    double value = Double.Parse("1.5");
}
catch (FormatException) { /*...*/ }

// TryParse promises just to *try to parse* and not being
// able to is unexceptional.
double value;
bool result = Double.TryParse("1.5", out value);

Consequently, if you change the error handling mechanism of a method, the name of the method should probably change too.

One thought on “How exceptionality and naming are linked

  1. Simo H says:

    In Symbian, this is actually codified in the coding convention.
    Basically, if a function can throw an exception (“leave”)
    then its name ends with L as in AppendL.

    With this convention, there would be two variants:
    double Double::ParseL( const TDesC& aString ) – leaves if it fails
    TInt Double::Parse( const TDesC& aString, double& aValue ) – returns an error code if it fails

    Having it in coding convention has some “interesting” (in the send of mind-numbingly boring) consequences though.

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