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;
}
}