In public classes, use accessor methods, not public-fields

Occasionally, you may be tempted to write degenerate classes that server no purpose other than to group instance fields:

Because the data fields of such classes are accessed directly, these classes do not offer the benefits of encapsulation. You can’t change the representation without change the API. If a class is accessible outside its […]

Continue reading

Minimize the accessibility of classes and members

The single most important factor that distinguishes a well-designed module a poorly designed one is the degree to which the modules hides its internal dara and implementation details. A well-designed module hides all of its implementation details, cleanly separating its API from its implementation. Information hiding doesn’t cause on itself good performance, it enables effective […]

Continue reading

Consider implementing Comparable

Comparable interface provides compareTo method which is similar with Object’s equals method, except that it permits order comparisons in addition to simple equality comparisons, and it is generic. By implementing Comparable, a class indicates that its instances have a natural ordering. Sorting an array of objects that implement Comparable is as simple as this:


Continue reading

Always override hashCode when you override equals

A common source of bugs is the failure to override the hashCode method. You must override hashCode in every class that overrides equals. Failure to do so will result in a violating of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet […]

Continue reading

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