Java Reference
In-Depth Information
implementation of n -to-1 (or 1-to-1) associations using the many-to-one
association idiom.
Testing the implementation is an essential aspect of the development.
There are several strategies and methodologies; two very simple approaches
are described by the equals method testing and toString method testing
design patterns.
Idiom
Read-only attribute
Context
A class has a read-only attribute.
Problem
It must be ensured that nobody can modify the attribute.
Forces or tradeoffs
It must be easy to read the attribute.
It must be impossible to write it.
Solution
The attribute is implemented as a private member
attribute of the class. A getter method with the same
name as the attribute provides read access to the
attribute. If the type of the attribute is a primitive type
(e.g. int ) or a non-modifiable class (e.g. String ) the
attribute can be directly returned by the method, other-
wise a copy of the attribute should be returned.
Since the attribute must be initialized at some point, the
constructor is responsible for this.
Examples
class SampleClass {
private String name;
public SampleClass(String name){
this .name # name;
}
public String name() { return name; }
}
Force resolution
Access to the attribute is easily achieved through the
method with the same name. Since the attribute is
private, it is not possible to modify it.
Design rationale
The getter method returns the value of the attribute
avoiding direct manipulation of the attribute by the class
clients. The simplest form of the getter method is just a
return statement having the attribute as argument. If the
attribute is a primitive type then it is passed “by value” to
the method caller. Otherwise, if it is an object, the caller
obtains a reference. In the latter case a problem arises:
since the client obtains a reference to the object, nothing
can avoid modification. Therefore a simple return
statement is suitable only for non-modifiable classes.
When a modifiable class is concerned, the getter method
must return a copy of the attribute.
Search WWH ::




Custom Search