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
Utility Classes We should note that all methods we put in the utility class should be static.
Utility classes can help you reduce repetition in your CSS and inadvertant irregularity in your style. This benefit, however, is negligible if you use a preprocessor. The reuse of single-rule classes like . float-left merely shifts repetition from CSS to HTML.
Utilities are simple HTML classes typically scoped to a single CSS property, like border-style or background-color . Utilities can be used additively to style an object from scratch or to override a style defined in component CSS.
A utility class is a special case of a helper class in which the methods are all static. In general, helper classes do not have to have all static methods, but may have instance variables. Multiple instances of the helper class may exist as well.
Is this the "correct" way of doing things or should we be instanciating the utility class as and when we need it?
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With