Besides the general principles of Why use getters and setters/accessors? I try to answer that with an example, and focus on the usage class-internally as this is your question.
One thing for clarification: In Java there are two classes to represent a point in time regarding Coordinated Universal Time (UTC) where both have a method to get their value, which is in milliseconds, i.e. Date#getTime
and Instant#toEpochMilli
.
Imagine a class in two versions using Java:
class Data {
private Date date;
public Date getDate() {
return date;
}
public long getMillis() {
return date.getTime();
}
}
class Data {
private Date date;
public Date getDate() {
return date;
}
public long getMillis() {
return getDate().getTime();
}
}
Note that the first version uses the field directly while the second version uses the getter.
Now imagine I want to change the type of date
to Instant
thus I have to change the versions as follows. I will do minimal effort in changing. The first thing to change is obviously the field itself.
private Instant date;
The second thing to change is the getter. But how? Do we change it to return the new type or do we a conversion?
public Instant getDate() {
return date;
}
public Date getDate() {
return Date.fromInstant(date);
}
Depending on how we changed the getter the method that uses the getter changes as follows.
public long getMillis() {
return getDate().toEpochMilli();
}
public long getMillis() {
return getDate().getTime();
}
As you can see, when we change the getter to convert from the previous type to the new type, we don't have to change the using method at all.
The version of the method that accesses the field directly has to be changed as follows.
public long getMillis() {
return date.toEpochMilli();
}
Now I hope this clarifies the benefit of using the getter inside the class itself. You will have less effort to put in when refactoring the code. But is it worth it?
Maybe you don't want to use the previous type anymore at all. Maybe the trouble to refactor the class is minimal. Maybe the factor readability comes into place. How will the class potentially change, may there be a functionality in the getter in the future? Are there conventions in my company?
All those questions' answers depend on the specific use case thus there is no generalized answer.
Anyways, I suggest to use the fields directly as (from my experience) the refactoring doesn't hurt and brings more benefits most of the time. You will have cleaner code and no strange mixtures of concepts. If you are not sure, just do the most simple and readable solution.
The answer disregards the case where the getter/setter does more than just getting/setting the field. In that case you obviously always want to use the getter/setter.