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.