We currently have a utilities class that handles a lot of string formatting, date displays, and similar functionality and it's a shared/static class.
Is this the "correct" way of doing things or should we be instantiating the utility class as and when we need it?
Our main goal here is to reduce memory footprint but performance of the application is also a consideration.
PS. We're using .NET 2.0
If there is any state in the class at all, then it is best to make objects out of it. Singletons are a pain, with respect to object dependencies, and thread safety.
If there is no state in the class, then the choice about whether to make it a static or not will have no appreciable affect on memory footprint.
If your language supports it, make these functions part of a package/namespace/module instead of a class.
If not, static methods of a class are fine. You should mark the class final/closed/nonvirtual/non-extendable if your language supports it.
If your language supports it, you can consider re-defining the built-in classes/definitions for the types those functions accept, but be wary of namespace collisions. In this case, defer to the style guide or de facto standard of your language of choice to choose the idiomatic approach.
Static classes are fine for what you described - just be careful that any shared state (static member variables) is shared in a thread-safe manner.
If you are using .NET, have you looked into using extension methods? I have found that with appropriate use I may not even need a utility class at all.
From OOD point of view it depends :-)
For pure functions you should use static methods in Java/C#. In C# you can also try to use extension methods as others describe.
For utility methods which are not pure functions (for example reading some file) you should create an instance to improve testability (allow mocking for example).
The difference is that the latter, although don't keep any state directly, they communicate with some external components having own, possibly changing state. This external state may cause this utility method to return different results over time (for the same input) making it much harder to test and to reason about. It is good design principle to distinguish between pure functions and such utility methods by putting the latter as explicit instance methods.
However in Java practice "mocking argument" usually takes preceeding, since it doesn't allow to mock static methods.
Is this in .NET? If so, it may better to provide extension methods. E.g. if you have an utility method that formats a string, change its signature from
to
This way, the
SpecialFormat
method will be far more discoverable since it will appear as a method on string.