Java Tip #5: Shorter singleton calls

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();

2 thoughts on “Java Tip #5: Shorter singleton calls

  1. Andi Post author

    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 as MySingleton.mySingleton(). Of course, when I import a method named getInstance(), 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.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.