Effective in Java Book Summary Part I

It is about writing programs that are clear, correct, usable, robust, flexible, and maintainable.

Creating and destroying Object

  • Consider static factory methods instead of constructors.

One advantage of static factory methods is that, unlike constructors, they have names.

  • Consider a builder when faced with many constructor parameters.

Builder pattern is a good choice when designing classes whose constructors

or static factories would have more than a handful of parameters, especially if most of those parameters are optional.

  • Enforce the singleton property with a private constructor or an enum type.
  • Enforce noninstantiability with a private constructor.
Such utility classes were not designed to be instantiated: an instance would be nonsensical.
In the absence of explicit constructors, however, the compiler provides a public,
parameterless default constructor. To a user, this constructor is indistinguishable from any other. 
Attempting to enforce noninstantiability by making a class abstract does not work.

The class can be subclassed and the subclass instantiated.

// Noninstantiable utility class
 public class UtilityClass {
// Suppress default constructor for noninstantiability
private UtilityClass() {
 throw new AssertionError();
 ... // Remainder omitted } //Because the explicit constructor is private,
//it is inaccessible outside of the class.
  • Eliminate obsolete object references
  • Avoid creating unnecessary objects. Reuse can be both faster and more stylish.

An object can always be reused if it is immutable

  • Avoid finalizers. Finalizers are unpredictable. You should never depend on a finalizer to update critical persistent state.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: