If you are using the Singleton pattern, you often have code like this:
Object myValue = MySingleton.getInstance().getSomeValue();
Can this be shortened? Yes! Like in Java Tip #3, we can use public static methods and static import. But then, we do not see at a glance what getInstance() is actually returning, and if we use multiple Singletons within our class, we would have a naming problem. The easy solution: rename the getInstance() method to the (camelCase) name of its class. Now we can write:
Object myValue = mySingleton().getSomeValue();
According to Oracle docs static imports should only be used sparingly.
What do you think ?
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
http://stackoverflow.com/questions/420791/what-is-a-good-use-case-for-static-import-of-methods
In my opionin, it depends – as always – how you use a specific feature.
Orcale says: “If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import.” – I think it depends on the naming of the imported methods and fiels. When I import
mySingleton()
, it is not only shorter, but at least as readable asMySingleton.mySingleton()
. Of course, when I import a method namedgetInstance()
, it is much harder to guess what this means.As another example, I very often use methods like alist(…) which is essentially
new ArrayList<T>(...)
, but with the type automatically inferred – very handy! Although this became better with Java 7, it is still very useful, even shorter and still very readable.