The art of generic code

In the past I’ve posted a pretty nice example of efficient code. These days, I’ve written this incredible simple but usefull functionality for fields:

    1     public static class FieldUtil<T> where T : Sitecore.Data.Fields.CustomField

    2     {

    3         /// <summary>

    4         /// Returns a field implicit casted to the required type(T) and logs a warning in case of the field doesn’t exist.

    5         /// </summary>

    6         /// <param name=”currentItem”>Item to read the field from</param>

    7         /// <param name=”fieldName”>Field name</param>

    8         /// <returns>The casted field retrieved from the currentItem or null.</returns>

    9         /// <exception cref=”T:System.ArgumentException”>Occurs when the currentItem is null or the fieldName is null or empty the method return.</exception>

   10         public static T GetField(Item currentItem, string fieldName)

   11         {

   12             if(currentItem == null)

   13             {

   14                 throw new ArgumentException(“The argument with the name ‘currentItem’ cannot be null.”);

   15             }

   16             if(string.IsNullOrEmpty(fieldName))

   17             {

   18                 throw new ArgumentException(“The argument with the name ‘fieldName’ cannot be null or empty.”);

   19             }

   20 

   21             T result = null;

   22 

   23             if (currentItem.Fields[fieldName] != null)

   24             {

   25                 result = currentItem.Fields[fieldName] as T;

   26             }

   27             else

   28             {

   29                 string warningMessage = string.Format(“Couldn’t find field with the name ‘{0}’ in item with the id ‘{1}’.”, fieldName, currentItem);

   30                 Sitecore.Diagnostics.Log.Warn(warningMessage, new object());

   31             }

   32 

   33             return result;

   34         }

   35     }

Because of the simplicity and the generic functionality of these 35 lines of code, do I nominate this snap as code of the day…

One thought on “The art of generic code”

  1. efficient and neat, very good man!

    hey, that could be a fun thing to do as well.. code of the day / week / month / year..

Comments are closed.