Self-encapsulate fields

Within the implementation of a class, it's 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   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -