Search code examples
javaprivateencapsulationgetter

Getter Pattern Within Class?


I have a field in a class that should only be accessed directly from a getter. As an 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());
  }
}

So even within the class itself a function like getFormattedCustomerInfo should not be able to access it via customerName_. Is there a way to enforce a class not access a field directly aside from the provided getter function?


Solution

  • It looks like you are trying to cache the database value, and want to protect against accessing a value which has yet to be cached.

    If this is true, then the variable customerName_ should not exist in the CustomerHelper class; the cached value should exist closer to the database.

    The method customerDatabase.readCustomerNameFromId(customerId) should first look at a cache, and if the cache is empty, call the database and cache the result.

    Effectively, customerName_ becomes a value in the cache: Map<Integer, String> cache where the key is customerId.