shortcuts don’t

Forcefully moving to a new computer sometimes leads to windy ways of encountering things you once wrote. Thoughts flash through the mind. Is it possible to instantiate a singleton at class loading time? Is class loading thread safe? Could it be as easy as instantiating the singleton object in a static block just like… 

No. I’m possibly not the first one coming up with that shortcut. And class loading happens to be thread safe. That’s good. But a loaded class is identified by its fully qualified name in combination with the identification of the class loader that loads the class. That makes it possible – feasible even – that a class is loaded by more than a single class loader and consequently a static block in the class file is executed more than once.

See? There are no shortcuts. Just do it the ‘proper way’. 

static data, static methods, singletons, factories and utilities

I think that the Java keyword ‘static’ is an inheritance from C. Most of the time saying that a method is static is a way to say that the method is a class method – that is, a method that operates on the type – as opposed to an instance method – that is, a method that operates on an instance of the type.

One of the best examples of static methods are constructors. They only can operate on a class even if they create an instance of that class as a result.

Now let’s have a look at singletons, utility classes and factories.

Singletons

Singletons obviously rely on the fact that if one declares a class member static it can only occur once per class for every instance of that class. Combine that with the fact that a class is unique in the context of a program then you realize it is a good way to implement a singleton. Not the only one but a good one. Now, if you want to be able to access the singleton object then you can use a static method to do that. You don’t need to but it is the easiest way. As soon as one has access to the singleton object, everything returns to normal and you can use the object to call any instance methods as you wish. If you want to implement a singleton in a multithreaded environment make sure that the method to retrieve and instantiate the singleton on demand is synchronized so that instantiating more than one instance of the singleton class is ruled out. For what it is worth, in most cases the static method that gets the singleton instance is called getInstance():

public class Singleton {
    private static Singleton instance = null;
 
    // Make sure we cannot instantiate this class from the outside
    protected Singleton() {
    }

    // Retreive te instance creating it if necessary. Synchronize to prevent race conditions.
    public static synchronized getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Utilities

Utility classes use class methods because it is a way to ‘scope’ global functions. Since Java requires the use of a class it is the only way to write something that resembles a regular function. I must say that scoping functions by their aspect is a good thing. Most of the time it turns out that this way the intent of a utility function is communicated in a better way.

Factories

Factories are in fact utility classes that ‘produce’ things. Objects of a certain class mostly. Because factories are collections of one or more utility functions that call a constructor based on a particular set of arguments without the need to have more than one instance it is convenient to implement that as a class solely containing a set of class methods.

unit testing and time travel

Sometimes the solution for a thorny problem is easy. If you are writing unit tests for a piece of code that behaves differently before and after a certain point of time you wish you could do time travel with the computer you are using to run the tests. Adjusting the system date often is inconvenient. A lot of processes depend on proper timekeeping by the operating system and often a regular user cannot adjust time for simple lack of authorization. Take my advice and stay away from the system clock.

The solution is to use Joda Time. It has a class called DateTimeUtils with a static method setCurrentMillisFixed that effectively fixes the system time for the Joda Time library to a certain value. Returning to the present is done by calling setCurrentMillisSystem after you are done time traveling

    @Before
    public void before() {
        LocalDate pointInTime = new LocalDate().minusDays(10);
        DateTimeUtils.setCurrentMillisFixed(pointInTime.toDateTime(new LocalTime(0, 0, 0, 0)).getMillis());
    }

    @After
    public void after() {
        DateTimeUtils.setCurrentMillisSystem();
    }

Done.

Enjoy.