Defensive Programming – Let Type Checking Work for You

Since I have been a speaker and a teacher, I have always stressed the importance of practicing proper object-oriented programming (OOP) techniques. If you don’t practice OOP, no matter what language you are using, I guarantee you will end up with a “house of cards” and they all eventually fall.

The first “pillar” of OOP is encapsulation which means the practice of data hiding. No code gets to the data in the type unless it uses properties or methods. As I always say, “bad data in, bad data out”. If that bad data gets saved to a database it could get corrupted, it could upset customers and will cause more work and money to fix it. Is this a good example of OOP coding?

public class OrderData
{
    public string ORDER;
    private string wearhouseId = "";
    public string OrderNumber = "";
    public string openClosed = "";
    public string transType = "";
    public string dateOpened = "";
    public string dateClosed = "";
    public string dateArchived = "";

    public OrderData(string _ORDER)
    {
        this.ORDER = _ORDER;
    }
}

NO, it is not! This type, currently in production, does not practice good encapsulation since the actual code contains over 198 public string fields! I would say over 90 percent of code I see as a consultant does not even get this first pillar right. The first line of all your properties and methods should be validating the data before proceeding.

To make this easier, always use proper data types since they will help you with validation. If the type needs a date, then use DateTime. If the type needs a URL, then use the Uri type etc. If, I had the code base to the type above, I would have change it to something like this.

public class OrderData
{
    public string Order { get; }
    public DateTime? DateClosed { get; private set; }
    private DateTime? _dateArchived;

    public OrderData(string order)
    {
        this.Order = order;
    }

    public DateTime? DateArchived
    {
        get { return this._dateArchived; }

        set
        {
            if (DateClosed.HasValue && value < DateClosed.Value)
            {
                throw new ArgumentInvalidException("DateArchived 
                            must be greater than DateClosed date.");
            }
            else
            {
                this._dateArchived = value;
            }
        }
    }
    //Code removed for brevity
    }

As you can see in the code above, I’m using the proper data types. I am also validating  data coming into the type and if it fails, I throw the proper exception.

If you use proper data types then I guarantee this will help your team. If you are a Microsoft .NET developer, please be sure to pick up a copy of my coding standards book. Please share comments you might have below.