Tuesday, May 14, 2013

Emptytons - Mimicking Static Classes in Java


A static class is one that has only static methods (functions) and it is meant to support procedural programming. Such classes aren't really classes in that the user of the class is only interested in the helper functions and not in creating instances of the class. While static classes are supported in C# [1], no such direct support exists in Java.

People often mimic this feature by using a private constructor for their class:
    public class StaticClass1 {
        // disallow instance creation by other classes
        private StaticClass1() {
            super();
        }

        public static boolean isEmpty(final String s) {
            return s == null || s.isEmpty();
        }
    }
But, this doesn't truly disallow creation of instances. Code (static initializers, methods, inner classes, etc.) written inside the class can still create instances of the class despite the private constructor. A dedicated Java hacker can even revert to reflection to create instances of the class.

Java does however provide support for enums and that can be handily used to create these static classes or Emptytons who can truly avoid creation of any instances:
    public enum StaticClass2 {
        // Empty enum trick to avoid instance creation
        ; // this semi-colon is important

        public static boolean isEmpty(final String s) {
            return s == null || s.isEmpty();
        }
    }
Reflection cannot be used to create instances of such classes unlike with private constructors as reflective instantiation of enum types is prohibited [2, 3].





[1] http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx
[2] http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9
[3] http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Constructor.html#newInstance%28java.lang.Object...%29

--