Search code examples
javaoopencapsulationsoftware-designeffective-java

It''s never a good idea for a public class to expose fields directly, but why it is less harmful if the fields are immutable?


I'm reading an article from Effective Java Item 14 - In public classes, use accessor methods, not public fields. In the book it says: While it’s never a good idea for a public class to expose fields directly, it is less harmful if the fields are immutable.

My question is why it's less harmful if the fields are immutable? Could you give a real-life example to justify? Here is the code example in the book.

/ Encapsulation of data by accessor methods and mutators
class Point {
   private double x;
   private double y;

   public Point(double x, double y) {
      this.x = x;
      this.y = y;
   }

   public double getX() { return x; }
   public void setX(double x) { this.x = x; }

   public double getY() { return y; }
   public void setY(double y) { this.y = y; }
}

While it’s never a good idea for a public class to expose fields directly, it is less harmful if the fields are immutable.

// Public class with exposed immutable fields - questionable
public final class Time {
   public final int hour;
   public final int minute;

   public Time(int hour, int minute) {
      this.hour = hour;
      this.minute = minute;
   }
}

Solution

  • If your object has solely immutable fields, most likely that object itself can be regarded immutable.

    Which means: upon creation, that object will never change its content. Thus you can reference to that object from any number of places. And no other object needs to worry that the corresponding data will magically change, because some other code did something.

    Essentially, the difference between direct field access and providing a setter method isn't what matters! The only thing that makes a huge conceptual difference: mutable vs immutable.

    And note: ideally, the public methods of a class provide you behavior that client code can use!