Do not punish the consumer with exceptions


We all write code an we all consume other peoples code. I know that it is easier to put your brain on autopilot and just throw exception for every minuscule thing that the consumer does wrong. But we should not. If we can fail gracefully or even recover from invalid input or internal errors then we should do so.

Take the following code as an example:

public IEnumerable<Product> GetProducts(IEnumerable<Guid> productIds)
{
  if(!productIds.Any())
    throw new ArgumentException("At least one id must be passed");

  // Getting the products from the database and...
}

I find this code a little hars on the consumer. If he passes an empty list of ids he gets an ArgumentException. I think that this code can be made friendlier for the consumer.

<pre>public IEnumerable<Product> GetProducts(IEnumerable<Guid> productIds)
{
  if(!productIds.Any())
  {
    Log.Warning("Method called with empty list. Returning empty list as result");
    return new List<Product>();
  }

  // Getting the products from the database and...
}

In this case the consumer will get a empty list of products and he can continue. If it becomes apparent that the consumer made a mistake. You can look into the logs and see what happened.

I think that this is much more user friendly.

Advertisements

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