Defensive programming

In a code review this week, an interesting issue came up. A simplified example of the issue was as follows:

    public class Customer
    {
        public Customer()
        {
            Orders = new List<Order>();
        }
 
        public List<Order> Orders { get; private set; }
 
        public Order GetOrderById(int orderId)
        {
            foreach (Order order in Orders)
            {
                if (order.Id.Equals(orderId))
                    return order;
            }
            return null;
        }
 
        public int OrderCount()
        {
            return Orders.Count;
        }
    }
 

 

Do you see the issue? The very subtle problem with the above is that all of the members of that class all trust each other, completely. We all know that we should “never trust data from outside of your context”, but that applies at the company level, at the department level, at the program level, at the screen level, and even at the method level. (In my best mobster voice) “Don’t trust no one!!”

So above, GetOrderById “assumes” that Orders is going to not be null. It’s just blindly using it, trusting completely that it can’t possibly be null. You might argue that since it’s initialized in the constructor, and the setter is private, what is the danger? The danger is the real world. Let’s say you roll of this project. Another developer rolls on. Unbeknownst to him, the success of this entire class hinges on that one line of code in the constructor. There is a lot of “trusting code” here, which can easily be broken. What if he makes the setter of Orders public? Now you have a ton of code that will absolutely fail, if Orders is ever set to null!

Likewise, OrderCount just blinding assumes that Orders is populated.

What is the answer then? The answer is to always program defensively. In your context (your method), make sure it is impossible for your code to fail. Here is a safer way to do this, with just an extra couple of lines – this is cheap insurance (forgive the formatting Windows Live Writer is freaking out, and I can’t fix it!)!!

    public class Customer
     {
         public Customer()
         {
             Orders = new List<Order>();
         }
 
         public List<Order> Orders { get; private set; }
 
         public Order GetOrderById(int orderId)
         {
             if (Orders != null)
             {
                 foreach (Order order in Orders)
                 {
                     if (order.Id.Equals(orderId))
                         return order;
                 }
             }
             return null;
         }
 
         public int OrderCount()
         {
             if (Orders != null)
                 return Orders.Count;
             else
                 return -1;
         }
     }

As you can see, we just add a quick check to see if Orders is null. This future-proofs this code, in case a future developer is not aware of this dependency. The ideal would be that every method, in isolation, should be able to “answer” any question. For example: “What if there is no config file?”, “What if the strings that were passed in, were null or String.Empty?”, etc. If you do that, you cover all of your assumptions. As I’ve said many times “Assumptions are at the root of all software bugs.” – so if you get rid of your assumptions, you help your code become more predictable and stable. And is that what we all want?!

Posted in Best-practices, Uncategorized
2 comments on “Defensive programming
  1. […] Defensive programming […]

    Like

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

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 5 other followers

%d bloggers like this: