Tuesday, December 24, 2013

Using Generics for maintainability

Generics are a great way to keep code maintainable. While it does add some overhead the maintainability pays off greatly.

Here's the Generics in C# guide from Microsoft: http://msdn.microsoft.com/en-us/library/512aeb7t.aspx

Here's a real example. In this specific case I am working on a Dynamics GP eConnect integration. I have to parse a whole bunch of lines into nasty looking eConnect objects like the sweet looking one below in the example. _parseSOPPaymentLine() maps SqlDataReader results to the eConnect object fields.


        private T[] ParseLines<T>(SqlDataReader reader)
        {
           
            List<T> lines = new List<T>();
            Type typeOfT = typeof(T);
            object o = null;
            while (reader.Read())
            {
                if(typeOfT ==                     typeof(taCreateSopPaymentInsertRecord_ItemsTaCreateSopPaymentInsertRecord))
                    o = _parseSOPPaymentLine(reader);
                /* check for other types */


                if(o != null)
                    lines.Add((T)o);
            }
            if (lines.Count == 0)
                return null;
            else
                return lines.ToArray();
        }

To call this
ParseLines<taCreateSopPaymentInsertRecord_ItemsTaCreateSopPaymentInsertRecord>(reader);


There are many benefits to using generics. In the example above my primary goal is to maximize maintainability, since i'm dealing with alot of types. Maintainability is a really important part of coding, it's not all about speed etc...

The alternative to using a generic function in this case would be to something like:
private object[] ParseLines(SqlDataReader reader, Type type)
{
//Basically replace "T" from the function above with "object", then do explicit casting
//Since we end up with a switch on the Type anyways, the first way makes the code much more clean, and
//therefore easier to maintain and extend
}

No comments:

Post a Comment

There was an error in this gadget