Getter patterns in classes?
I have a field in the class that can only be accessed directly from the getter. For example….
public class CustomerHelper {
private final Integer customerId;
private String customerName_ = null;
public CustomerHelper(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
if(customerName_ == null){
Get data from database.
customerName_ = customerDatabase.readCustomerNameFromId(customerId);
Maybe do some additional post-processing, like casting to all uppercase.
customerName_ = customerName_.toUpperCase();
}
return customerName_;
}
public String getFormattedCustomerInfo() {
return String.format("%s: %s", customerId, getCustomerName());
}
}
Therefore, even inside the class itself, functions like getFormattedCustomerInfo should not be able to access it through customerName_. In addition to the provided getter function, is there a way to force the class not to access the field directly?
Solution
There is no such mechanism in Java (or at least I don’t think there should be). If you determine that getFormattedCustomerInfo
should be prevented from accessing the customerName_
directly, create another class and combine them.
I would recommend CustomerInfoFormatter
.
Also, I’ll change customerName_
to customerName
because the language supports privacy by explicitly declaring and doesn’t need to add more indicators.