Thursday, April 05, 2007

Exception Raising v DBC

I was reading an article on DBC and realized that I disagree with some of the points.

In particular I think its better to specify the contract in .NET using the comment and associated exception, to me its far more meaningful for the parameter comment to say what the parameter is and an exception comment to explain anything else:

///

Gets the user for the given ID.
/// Should be > 0
/// is less than 0.
public User GetUserWithIdOf(int id, UserRepository userRepository)
{
#region Preconditions

ArgumentValidation.ThrowIfNegative(id, "id");

#endregion

This sort of approch is documented on code project.

One other thing that worries me is when people talk about using exceptions for "exceptional" circumstances. I personally buy more into the approach Microsofts "Framework Design Guidelines" book pushes for: "If a member cannot successfully do what it is designed to do, it should be considered and execution failure and an exception should be thrown".

Therefore if a repository has GetById and it can't get the object what do we do? Do we return null and leave it to the caller to decide what to do, or do we be more explicit and rename our method TryToGetById if it is not going to raise exceptions. I choose the latter and in fact NHibernate uses this sort of approach where ISession.Get does not raise an exception if it can't find the object but ISession.Load does.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

No comments:

Post a Comment