Java Reference
In-Depth Information
Sidebar 4.2 Read-only attributes
The OO purists say that all attributes should be private; getter and setter methods
that handle reading and writing the attributes should be provided as needed. In
practice, when an attribute is meant to be read-only it can be implemented in two
possible ways, depending on the context in which it will be used. The first is setting
it private and providing a public method that returns its value. This ensures that no
client of the class is allowed to change the attribute value. For instance:
private String readOnlyAttribute;
public String readonlyAttribute () {
return readonlyAttribute;
Another option is to use an attribute that is public (or package public). In this
case the clients of the class must know that the attribute is intended to be read-
only and conform to this implicit assumption. It is a good practice to associate a
comment that reminds of the assumption. For instance:
public String readOnlyAttribute; // Read-Only!!!
These two solutions provide different safety levels. While the first solution
works in every context, the second is acceptable only where the class clients know
very well the intended use of the attribute (e.g. the class is used only inside a
package and its clients are written by the same developer as wrote the class). In
addition to the above considerations, there are three other issues that should be
taken into account: ease of use, efficiency and flexibility.
The ease of use of the two solutions is almost the same for a client that needs to
access the attribute. The syntax required by the first solution involves a method
invocation, while the syntax corresponding to the second solution is a simple
access to the public variable.
When it comes to efficiency the first solution is clearly worse than the second
one. The difference is marked by the method invocation; it is far less efficient than
direct attribute access.
Finally, the flexibility of the first solution becomes evident when considering
the following scenario: several alternative implementations are required; the
common characteristics are defined in an interface that can be implemented by
different classes.
Class Item represents the items. The name is implemented as in class
Feature . In addition it has a one-to-many association to class Feature ; since
the number of the linked elements is known at the time the item is built, the
association can be implemented as an array of Feature elements ( features ).
The value() method returns the value of a feature, while the setValue()
method sets a new value for a feature.
public class Item {
private Feature[] features;
private String name;
private Feature category;
public Item(String name, Feature[] features){
this .name # name;
Search WWH ::

Custom Search