Enforce non-instantiability on static classes
Every project ends up with one or even possibly many static helper classes. If you program in Java, I'm willing to bet the house your project has a StringUtil class lurking around somewhere. These classes are easily abused, but can serve a valid purpose, such as a factory class responsible for creating instances.
If these classes contain only static methods (as they usually do), there is never any reason for them to to be instantiated. However, in both Java and C#, it's easy to forget that if you do not explicitly declare a constructor, the compiler will generate a no-arg constructor by default. The consequence is that the following code is valid:
StringUtil util = new StringUtil();
You've just allocated memory unnecessarily. Plus, the garbage collector will now incur extra overhead since it will have to reclaim this memory even though it was never actually used. All of the methods are static, so there is no reason to instantiate an individual object from this class.
To avoid instantiations, make sure you declare a private no-arg constructor. This will cause the compiler to throw an error any time the class is attempted to be instantiated.
public class StringUtil
{
// constructor marked private since all methods are static
private StringUtil() {}
// bunch of static methods not shown
}
A side note - If you are using C# 3.0, I recommend using extension methods to enhance the behavior of existing classes rather than creating a something like a dedicated StringUtil class. First of all, any class declaring extension methods has to be marked as static and cannot be instantiated. And more importantly, it provides a much cleaner implementation to add those helper methods directly on the affected class. The added bonus is that Visual Studio is smart enough to provide Intellisense for extension methods on targeted classes.
Sunday, June 22, 2008 9:35:25 PM (Eastern Standard Time, UTC-05:00)
Back To Basics | C# | Java | Programming