WEB4J - Minimalist Java Web Application Framework

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 :

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;
} 



See Also :
Lazy initialization
Would you use this technique?
Yes   No   Undecided   
Add your comment to this Topic :

© 2009 Hirondelle Systems | Source Code | Contact | License | Quotes | RSS
Individual code snippets can be used under this license - Last updated on January 4, 2009.
Over 100,000 unique IPs last month - Built with WEB4J.
- In Memoriam : Bill Dirani -