3

I am aware that using getters and making fields private has many advantages in general cases (data-hiding, decoupling, blah, blah, blah). What I'm asking is related specifically to immutable classes.

Let's say I've created a model class to store the data from a REST response, for example:

public final class Profile {
    private final int id;
    private final String name;
    private final String info;
    private final String location;
    private final URI avatar;
    private final Gender gender;
    // about 10 more fields
}

The class and its fields are all final and cannot be changed or overridden. Each field is an instance of an immutable class and is validated in the constructor. Also, every field needs to be publicly accessible (no data-hiding).

In such a case, what possible advantage could there be to tripling the size of the class to add getters for every field instead of just making the fields public?

Leo Aso
  • 11,898
  • 3
  • 25
  • 46

1 Answers1

1

Implementing the getters provides flexibility for future changes to the Profile class. If your class provides a getter you can change the underlying private member in the Profile class and it won't require changes to the consumers of your class. You do want to hide the data types of the class-level variables just as you want to hide the values.

nicomp
  • 4,344
  • 4
  • 27
  • 60