Archive for September, 2010

Configuration classes with Enums

As I mentioned on my previous post, an alternative implementation to create Singleton in Java is with Enum types.

Extending the idea, it is interesting to create classes which read configuration values from Properties files with Enum classes. Below is an example:

public enum Configuration {

    HOST("host"),
    PORT("port"),
    MAIL_SERVER("mailServer"),
    INPUT_DIRECTORY("inputDirectory"),
    OUTPUT_DIRECTORY("outputDirectory");

    private static Properties properties;
    static {
        properties = new Properties();
        try {
            properties.load(Configuration.class.getClassLoader().getResourceAsStream(
                "configuration.properties"));
        } catch (Exception e) {
            throw new RuntimeException("Error when loading configuration file", e);
        }
    }

    private String key;

    Configuration(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return properties.getProperty(key);
    }
}

Configuration classes which read values from properties files should be Singletons that are loaded once on the application startup time.

The Configuration values can be used this way:

System.out.println(Configuration.HOST.getValue());

This example shows that the key and value from properties are stored with Enum constants. They are type-safe, they can be easily accessed through code completion in your favourite IDE and they can take advantage of refactoring tools.

Tags: , , , ,

Singleton in Java with Enum types

Java 1.5 introduced the concept of Enum types. They are type-safe constants, which implements equals(), hashCode() and cannot be extended. Each constant can have attributes and override an abstract method created on each Enum class.

Although Singletons are not encouraged, the best way to create it is using Enum types. Here is an example:

public enum Singleton {
    INSTANCE;

    public void sayHello() {
	   System.out.println("Hello World!");
    }
}

And then you call it this way:

Singleton.INSTANCE.sayHello();

Using Enums to create Singletons brings the serialization mechanism already bundled in the Enum type. This technique is described on the Effective Java Second Edition book by Joshua Block.

Tags: , , , , ,