Do you have any input on how to organize and name utility classes?
Whenever I run in to some code-duplication, could be just a couple of code lines, I move them to a utility class.
After a while, I tend to get a lot of small static classes, usually with only one method, which I usualy put in a utility
namespace that gets bloated with classes.
Examples:
ParseCommaSeparatedIntegersFromString( string )
CreateCommaSeparatedStringFromIntegers( int[] )
CleanHtmlTags( string )
GetListOfIdsFromCollectionOfX( CollectionX )
CompressByteData( byte[] )
Usually, naming conventions tell you to name your class as a Noun. I often end up with a lot of classes like HtmlHelper
, CompressHelper
but they aren't very informative. I've also tried being really specific like HtmlTagCleaner
, which usualy ends up with one class per utility method.
Have you any ideas on how to name and group these helper methods?
Helper
suffix is a good convention, since it is used in other languages (at least in Java, IIRC rails use it).The intent of your helper should be transported by the method name, and use the class only as placeholder. For example
ParseCommaSeparatedIntegersFromString
is a bad name for a couple of reasons:FromString
suffix since it is deduced from signatureWhat do you think about:
I believe there is a continuum of complexity, therefore corresponding organizations. Examples follow, choose depending of the complexity of your project and your utilities, and adapt to other constraints :
At each grouping level (package, class) :
For projects, I usually repeat the common meaning in a superpackage name. Although not my prefered choice in theory, I don't see in my IDE (Eclipse) from which project a class is imported, so I need the information repeated. The project is actually only used as :
Static methods (except those using static class members) work without context, all data have to be passed as parameters. We all know that, in OO code, this is not the preferred way. In theory, we should look for the object most relevant to the method, and move that method on that object. Remember that code sharing doesn't have to be static, it only has to be public (or otherwise visible).
Examples of where to move a static method :
Although this method moving may seem for OO-purist, we find this actually helps us in the long run (and it proves invaluable when we want to subclass it, to alter an algorithm). Eclipse moves a method in less than a minute (with all verifications), and we gain so much more than a minute when we look for some code, or when we don't code again a method that was coded already.