C# – Naming collections of helper methods, and avoiding meaningless jargon words

clibrariesnamingnaming-standards

While coding anything remotely useful, I inevitably find myself wanting to add methods to perform smaller bits and pieces. (It could be a method to return everything in a string to the left of the first occurence of a particular character.) Over time, writing such methods will propably form into some kind of library.

What should we name such classes, or how should they be structured? The string method mentioned earlier should probably be in a class called "String something", but I think using suffixes like Utils, Helper, Manager, or Service only makes the name longer without adding real meaning. The name "StringMethods" isn't much better.

So how can we do organize and name our "helper" methods in a sensible way? Has anyone succeeded in doing this?

Best Answer

Naming

  • Use active verbs.
  • If a "helper class" is particular to custom classes, use domain terminology
  • Can helper methods be organized functionally rather than by data type? Then a usefully descriptive class name would be more forthcoming.
  • The class name and/or method signature tells a lot and will lessen the urge to put a data type as part of a method name.
  • Experiment! Be bold about changing class names. Y'all have version control, yes?

Structure

  • Prefer static methods and static classes. This conveys to me the intent that the methods are not stateful; references to arguments or computations results are not kept - and they shouldn't be.
  • Explicitly null any class level members after use. Don't keep object references. Do not fall for 'it doesn't matter as it will get over-written next time.' Hear me now and believe me later.
  • Helper class methods should treat arguments as immutable. These general purpose classes are not your domain classes and should not be altering domain class state.

Extension Methods

As suggested by @BenCottrell, is a good idea too.

  • These imply a close relationship to the type they work on. Closer than the typical 'helper class'
  • If you must change any domain object state I'd say create extension methods, don't use general purpose helper classes.
  • Define these w/in its own namespace,or nested namespace as needed to limit their scope. Otherwise an extension method on the string class for example will be available for all string objects everywhere. Namespacing emphasizes the extension's intended use for its intended targets.

Extension Methods vis-a-vis Helper Classes

  • These are not mutually exclusive
  • I see the difference as expressing something about their behavior as a design factor - treating objects as immutable or not. See above.
  • It is sometimes said that helper classes is a code smell, suggesting a closer look at the design is in order. After all, if these methods are intended to work on particular classes then perhaps that is where they should be.
Related Topic