Wednesday, February 16, 2011

Self-encapsulate fields

Within the implementation of a class, it is common to refer directly to private fields. There is another style, in which all internal references to fields are indirect, and proceed through the appropriate get and set methods. This is called self-encapsulation.
Self-encapsulation :
  • is needed for lazy initialization
  • is slightly more difficult to read than direct field access
  • can establish a synchronization policy for the field
  • allows subclasses to override the get and set methods, and provide their own definition of how fields behave
Example
public final class Infant {

  public Infant (final String aName, final int aWeight, final String aMood ){
    setName( aName );
    setWeight( aWeight );
    setMood( aMood );
  }

  public void becomeHungry() {
    //instead of fMood = "Cranky", use:
    setMood("Cranky");
  }

  public String toString() {
    //use get methods instead of direct access
    final StringBuilder result = new StringBuilder();
    result.append("Infant - Name: + ");
    result.append( getName() );
    result.append(" Weight: ");
    result.append( getWeight() );
    result.append(" Mood: ");
    result.append( getMood() );
    return result.toString();
  }

  public String getName() {
    return fName;
  }
  public void setName( String aName ){
    fName = aName;
  }

  public int getWeight() {
    return fWeight;
  }
  public void setWeight( final int aWeight ){
    fWeight = aWeight;
  }

  public String getMood() {
    return fMood;
  }
  public void setMood( final String aMood ){
    fMood = aMood;
  }

  //..other methods elided

  // PRIVATE ////
  private String fName;
  private int fWeight;
  private String fMood;
} 

No comments:

Post a Comment

Chitika