Immutable classes should be declared final
Use static method instead of constructor
i.e. String valueOf(int) instead of String(int)
Pro: descriptive names, can return existing object, great for immutable
Con: private constructor prevents subclassing
Use builder pattern instead of constructor with many parameters
Price p = new Price.Builder("AAAAAAAA9").bid(100).ask(101);
class Price {
static class Builder {
Builder(String cusip);
Builder bid(float);
Build ask(float);
}
}
Do not use finalizer due to severe performance penalty during garbage collection
Use Finalizer Guardian if class can be inherited:
Class Foo {
// create dummy object which calls the enclosing object's finalizer when garbaged collected
private final Object guardian = new Object() {
@Override protected void finalize() throws Throwable {
Foo.finalize();
}
}
}
boolean equals(Object obj) should always return false if obj is null
Use concurrency utilities instead of wait and notify
Use Enum type for singleton class construction and readResolve (serialization)
Use Executors and tasks instead of Threads
Avoid appending "Impl" to an interface name for a class as it is not descriptive.
Don’t mix array with generic. Arrays are covariant and reified; generics are invariant and erased. As a consequence, arrays provide runtime type safety but not compile-time type safety and vice versa for generics.