Minimize mutability

An immutable class is a simply class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object.

  1. Don’t provide any methods that modify the object’s state (known as mutators)
  2. Ensure that the class can’t be extended. This prevents careless or malicious subclasses from compromising the immutable behavior of the class by behaving as if the object’s state has changed.
  3. Make all fields final. This clearly expresses your intent in a manner that is enforced by the system.
  4. Make all fields private. This prevents clients from obtaining access to mutable objects referred to by fields and modifying these objects directly.
  5. Ensure exclusive access to any mutable components. If your class has any fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects.

Immutable objects are simple – an immutable object can be exactly in one state, the state in which it was created.

Immutable objects are inherently thread-safe; they require no synchronization, they can be shared freely.

The only real disadvantage of immutable classes is that they require a separate object for each distinct value.

//Immutable class with static factories instead of constructors
public class Complex {
  private final double re;
  private final double im;

  private Complex(double re, double im) {
    this.re = re;
    this.im = im;
  }

  public static Complex valueOf(double re, double im) {
    return new Complex(re, im);
  }
  ...
}

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.