Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: static util methods?
|
Posted: Mar 25, 2004 11:25 AM
|
|
static methods can also be inflexible. In some cases, it makes sense to have a singleton object that provides the methods (with a static getInstance(), of course). This can also facilitate unit testing and make later extension or changes much easier.
Providing this flexibility can be worthwhile, especially when there is a little bit of state associated with the operations involved.
For example, I created a "localized string provider" class (not in Java) that I made into a singleton object. I could have just had a static method getString( id, params ) that would have worked. Later when I wanted to use this facility in a different context, I was thankful that I had done it this way; by being able to substitute a different object (implementing the same interface, of course), it was a snap.
Certainly don't use performance as a justification for, or a reason to use static methods. Firstly, that's an eggregious act of premature optmization. Secondly, if testing and profiling reveals a real problem, making the singleton's method final should yield the same performance as a static method, since they are both not virtual (anyway, the slowness-of-virtual-methods bugaboo is being addressed well by JITs these days; see the last couple installments of Bill's interviews with Anders Hejlsberg on this, eg. http://www.artima.com/intv/choices.html).
I think static methods are good for utility methods which have and will never have any kind of state except that passed in by parameters. Some examples might be miscellaneous utility or helper functions, such as adding capabilities to the built-ins like the String class or the File class.
[/b]static[/b] methods can often be a little too static, so they should be used judiciously.
|
|