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. […]
When you switch from a language with manual memory management, suc as C or C++, to a garbage-collected language, your job as a programmer is made much easier by the fact that your objects are automatically reclaimed when you’re through with them.
It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both fast and more stylish. An object can always be reused if it is immutable. String s = new String(“string”); // DON’T DO THIS The statement create a new String […]
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 […]
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 […]
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 […]
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 […]