.NET, Archive, Software Design

Software Design Tip of the Fortnight: Tip #2

For this second installment of Software Design Tip of the Fortnight I want to talk a little about exceptions. Exceptions in .NET provide an excellent means of handling errors. We all know not to use exceptions for flow control, but there are many other ways to abuse exceptions.

Abusing exceptions can be anything from throwing the base Exception class, to throwing more than just exceptions. But the most common abuse of exception handling is to simply suppress them. We have all seen applications that do something similar to:

SomeBusinessObject bo = SomeBusinessObject.LoadWithId(4);
    bo.SomeIntValue = int.Parse(txtSomeTextField.Text);
   //the value wasn't int... so ignore it.

The problem with suppressing exceptions is that most components don’t just throw them for the fun of it, there is some underlying reason why the exception was thrown in the first place.

The above example appears innocent enough. Int32’s Parse method throws an exception if it cannot parse the input string. But what if in the future another developer decides that the business object’s SomeIntValue needs a certain business rules that limits the acceptable values.

public class SomeBusinessObject{
    //other class code

    public int SomeIntValue{
         get{ return _someIntValue; }
             if(value < 0)
                  throw new BusinessRuleException("Invalid value for SomeIntValue.");
             _someIntValue = value;

In this case the business object is enforcing a business rule that prevents negative numbers from being set. Now what happens is that the code from our first example silently fails if the business rule is violated. The solution in this case is to instead check the input value for validity to Int32 and then check for validity to the business rules. Or put simply, don’t suppress exceptions. You never know when your original assumptions will be changed.

Never miss an article! Subscribe to my newsletter and I'll keep you updated with the latest content.


About Jason

Jason is an experienced entrepreneur & software developer skilled in leadership, mobile development, data synchronization, and SaaS architecture. He earned his Bachelor of Science (B.S.) in Computer Science from Arkansas State University.
View all posts by Jason →

Leave a Reply

Your email address will not be published. Required fields are marked *