Avoid finalizers

Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. One shortcoming of finalizers is that there is no guarantee they’ll be executed promptly [JLS, 12.6]. It can take arbitrarily long between the time an object becomes unreachable and the time that its finalizer is executed. […]

Continue reading


Enforce noninstantiability with a private constructor

Occasionally you’ll want to write a class that is just grouping of a static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses. They can be used to group related methods on primitive values or […]

Continue reading


Enforce the singleton property with a private constructor or an enum type

A singleton is simply a class that is instantiated exactly once. Singletons typically represent a system component that is intrinsically unique, such as the window manager or file system. Making a class a singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements and interface that serves as its type. // Singleton with public […]

Continue reading


Consider a builder when faced with many constructor parameters

Static factories and constructors share a limitation – they do not scale well to large number of parameters. Consider a class representing the Nutrition facts label that appears on packaged food. These labels have a few required fields – serving size, servings per container, and calories per serving – and over twenty optional fields. Most […]

Continue reading


Consider static factory methods instead of constructors

One advantage of static factory methods is that, unlike constructors, they have names – ex: BigInteger(int, int, Random) – probably returns a prime number, it is much readable BigInteger.probabluPrime() Static factory methods, unlike constructors, they are not required to create a new object each they’re invoked. Static factory methods, unlinke constructors, can return an object […]

Continue reading