Cons of static utility classes in java?
What are the cons of creating static 开发者_JAVA技巧utility classes? The more I've made, the more I find them extremely useful. I understand that they lack object oriented design, but I still love them probably more than I should. Are there any other cons for their use?
There is nothing wrong with them, in the right context. If you have free-standing, stateless methods (such as those found in java.lang.Math
), then a static class is the perfect place for them. The only reason they're in a class at all is because Java has no concept of free-standing methods.
The main disadvantage IMO is the impossibility, using most of the mocking frameworks, to mock the implementation of such utility methods in order to unit-test some class using these utility methods.
For example, Using System.currentTimeMillis()
is easy to get the current time. But when you have to test a class which uses the current time to do some work, it's impossible to mock the method to make it return a specific point in time. Using an object implementing a Clock
interface and injected into the object to test make it much easier: you can create a mock Clock implementation returning a specific date when asked to get the current time.
I had talked about this sometime ago in a post which you can find here.
The chief problems in the usage of a static method are:
- Mockability as the other posters pointed out.
- Several versions of a static class can be loaded in an application depending on the class loader hierarchy and class path configured for the entire hierarchy of class loaders. (A third element is also if the class loader is configured as parent first or child first) Makes testing and debugging this a nightmare.
- A static method cannot be inherited from. Hence violates OCP (Open Closed Principle) i.e. a static method is not extensible. Look at Log4J for typical problems with static methods.
- A static method is not amenable for the application of either the Interface Segregation Principle or the Strategy pattern. It is not possible to have alternate implementations of a similar algorithm depending on individual use cases without recourse to copious amounts of hand written code sprayed liberally with "if conditions".
But if the method itself is not too cumbersome and is pretty much predictable (i.e. not too many requirements for different variations of the implementations etc.) then there is no reason why a static method would not fit the bill. So, moral of the story is Use it but be aware of side affects.
精彩评论