Monday, June 13, 2011

Convenience functions and utility classes

Convenience functions are a favorite category of mine. The core libraries provide great functionality but (by necessity) operate at an atomic level. You might want to call A,B and then C and I just want C then A. This flexibility is great but can lead to a lot of duplicated code in your application.

Enter a convenience function. This is what I call code that wraps several calls to base level functions that can be reused throughout the application. We group similar ones into a static class with a Utils suffix (e.g. StringUtils or XmlUtils).

Here is an example of one that we use:
/// <summary>
/// Convert either a predefined color name or an ARGB value into a Color object.
/// </summary>
/// <param name="colorString">Either a predefined color name or an ARGB number 
/// value represented as a string./// <returns>Color
public static Color FromColorString(string colorString) {
  // Color will throw an exception if the string is null.
  if (string.IsNullOrEmpty(colorString)) return Color.Empty;

  // Translate HTML color strings.
  if (colorString.StartsWith("#")) {
    return ColorTranslator.FromHtml(colorString);

  // See if the passed in value is a named color string.
  Color color = Color.FromName(colorString);
  if (color.IsKnownColor) return color;

  // If the string is not a named color and not a number return the empty color.
  if (!StringUtils.IsInteger(colorString)) return Color.Empty;

  // Otherwise convert the string to a number and return a color based on that.
  return Color.FromArgb(Convert.ToInt32(colorString));

It neatly wraps several ways to create a color object from an HTML string, named color or argb value. Create a bunch of unit tests for this and you have a nice piece of reusable code.

1 comment:

Anonymous said...

Life Saver