Wednesday, October 04, 2006

Use Beans for data encapsulation

Use Beans for data encapsulation

Often, more than one value needs to be returned from a method. This might be especially the case with lists/collections, where each item is a tuple of various values. Solution: Use a simple java bean (that has nothing to do with Enterprise Java Beans, EJB) to encapsulate the values. A nested public static class can be used well for this. A bean is defined by Sun as a class that
  • has a default constructor (no parameters), and either
  • has only public fields, or
  • public getXXX and setXXX methods for all private/protected fields XXX.
By the naming convention, a "bean property" value can be either published as public String value; or public String getValue() {...} public String setValue(String value) {...} E.g., in the OPC database access, each data item contains a timestamp and a float value. In this case, setXXX methods are not necessary as the constructor does this work.
public class OpcDataConnection ...
public static class DataItem {
  private Date mDate;
  private float fValue;
  public Date getDate { return mDate; }
  public float getValue { return fValue; }
}
...
}
The same Beans are also used in many other cases in Java, e.g.
  • in jsp pages, such a bean can be directly accessed as property value dataItem.value, dataItem.date
  • such beans can be serialized and stored in an XMLEncoder

No comments: