Thursday, September 25, 2014

Designing Your Application to be Unit Testable

The easiest way to structure any application so that it is unit testable is to break up the main sections of the work being down into some basic pieces.  These are:

  1. Get your data
  2. Do work with your data
  3. Commit changes to your data
With this basic application structure you can now separate the pulling and processing of the data.  You are in complete control of that data being used by the processing code and can manipulated it as you see fit.  It is the ideal structure for unit testable code.  

public class MyMainWorker
{
    public void RunWorker()
    {
        // Optional begin your transaction here
        DataSet ds = GetData();
        object o = Execute(ds);
        // Begin your transaction
        SaveData(ds);
        // Commit your transaction
    }

    private void SaveData(DataSet ds)
    {
        throw new NotImplementedException();
    }

    private object Execute(DataSet ds)
    {
        throw new NotImplementedException();
    }

    private DataSet GetData()
    {
        throw new NotImplementedException();
    }
}

Wednesday, September 24, 2014

?? Operator is great for defaulting objects

If you need to default an object, an easy way to do this is with the null-coalescing operator.  In this example I need to default MyTempClass if I cannot pull it from another location.

using System;

namespace Tips
{
    public class NullCoalescingOperator
    {
        public void RunTip()
        {
            MyTempClass myTempClass = null;
            MyTempClass myOtherTempClass = new MyTempClass()
            {
                MyProperty = 1
            };
            MyTempClass x = myTempClass ?? myOtherTempClass;
            Console.WriteLine("{0}", x.MyProperty);
        }
    }

    public class MyTempClass
    {
        public int MyProperty { get; set; }
    }
}

Tuesday, September 23, 2014

Building File and Directory Paths

I see directory and file concatenation done with string append all too often. There are built in .Net libraries that help you do this so much easier. When you are working with file and directory paths, use System.IO.Path.Combine().
using System.IO;

namespace Tips
{
    class Program
    {
        static void Main(string[] args)
        {
            Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonPictures),
                "First SubDir",
                "Second Subdir",
                "MyFile.jpg");
        }
    }
}