January 23, 2007

Helpers vs. Cruft

I'm pretty certain that most programmers out there have little snippets of code that they use as helpers almost everywhere they go.

Coders who use Oracle and .NET will often create parameter helper methods like...
public static OracleParameter CursorParameter(string parameterName)
{
OracleParameter parCursor = new OracleParameter(parameterName,OracleType.Cursor);
parCursor.Direction = ParameterDirection.Output;
return parCursor;
}
People who have to deal with title-case in ASP.NET often have to resort to funky items like...
public static string FormatTitleCase(string s)
{
// (.NET 1.1) This "hack" works in both Windows Forms and ASP.NET.
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(
s.ToLower(System.Globalization.CultureInfo.InvariantCulture) );
}
There is nothing wrong with creating little helper snippets like this. I actually encourage their creation, as long as they end up getting centralized as they're created.

On one of the side contracts I'm working right now on top of my primary contract, I'm dealing with a codebase where this guy has about fifty of these little helpers...but every single place where they would be used, they're simply copy/pasted into place into the codebase. Database code, security code, etc., the same code doing the same thing hundreds of times...a breeding ground for maintenance bugs. I've been finding myself refactoring these helpers into actual helper classes to make the code easier to follow, as well as ensure that any bugs found in one helper result in a bug fix everywhere that helper is used.

It may take a little longer to do up front, but in the long run, it saves time and effort and results in a smaller, more stable codebase.

3 comments:

Sarkie said...

My insists making Helper classes with meaningful helper method names.

"GetCustomerCodefromCustomerID"

Put it into the CustomerHelper Class, it is quite nice once you start coding like this. One place to add the helpers, one place to update if it is broken.

But copy and pasting is so easier ;)

Helibear said...

Hello. Are you related to Emma and Chris. I know that's a bit random but, hey.
h x

Michael Russell said...

Sorry, no relation.