Tuesday 1 September 2015

Defensive code

Defensive code is the concept of pro-actively catching errors before they occur, it puts the onus on the developer to write code that will prevent exceptions from occurring. Instead of taking data in and blindly casting it to the types we expect, we first check to ensure that the conversion won't throw an expectation.

We've already gone over this defensive code concept in practice earlier when we leveraged the tryParse or the 'is' or 'as' operators, all these constructs are here for us to prevent errors from occurring.

the idea behind defensive code is to prevent exceptions, our goal is to validate our data or what we are trying to do, before an exception is thrown. Hence we are ensuring that code which could though an exception, won't because it will never be executed.


using System;

namespace pc.defensiveCode
{
    class Person { }

    class Dog { }

    class Program
    {
        static void Main(string[] args)
        {
            var str = "12g3";
            int i;

            // We test to see if our 'str' variable is an int
            // rather than assume it is
            if (int.TryParse(str, out i))
                Console.WriteLine($"\"{str}\" is an int");
            else
                Console.WriteLine($"\"{str}\" is not an int");

            object o = DateTime.Now;

            // We test to see if our object 'o' is a DateTime
            // rather than assume it is
            if (o is DateTime)
                Console.WriteLine($"{o} is a valid date time");
            else
                Console.WriteLine("the value of o is not a valid date time");

            o = new Person();

            if (o is Person && o is Object)
                Console.WriteLine("o is a person and object");
            else
                Console.WriteLine("o is not a person and object");

            // We use the as operator to unbox our object
            // as a person
            var p = o as Person;

            // We test to see if our object 'p' is a not null
            // rather than assume it is
            if (p != null)
                Console.WriteLine("p is a person");
            else
                Console.WriteLine("p is not a person");


            // We use the as operator to unbox our object
            // as a dog
            var d = o as Dog;

            // We test to see if our object 'd' is a not null
            // rather than assume it is
            if (d != null)
                Console.WriteLine("d is a dog");
            else
                Console.WriteLine("d is not a dog");
        }
    }
}


this is more of a concept than a construct, but defensive code is good code.