Java Reference
In-Depth Information
Idiom
Constrained-value attribute
Context
A class has an attribute that has constraints on what
values it can assume.
Problem
Ensure that only allowed values can be assigned to the
attribute.
Forces or tradeoffs
It must be possible to easily read and write the attribute.
Forbidden values must be avoided.
Solution
This idiom is an extension of the “read-only attribute”
idiom.
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.
A
setter
method with the same name as the attribute
provides write access to the attribute. The
setter
method
checks if the new value is allowed; if it is, the attribute is
updated. Otherwise an exception is thrown.
The attribute must be initialized at some point; usually it
is the constructor that is responsible for initialization.
Examples
private
String value;
// getter method
public
String value() {
return
value; }
// setter method
public void
value(String newValue)
throws
IllegalArgumentException {
if
(satisfiesConstraints(newValue)){
value
#
newValue;
return
;
}
throw new
IllegalArgumentException(
"value '"
!
newValue
!
"' not valid for attribute "
!
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 “read-only attribute” idiom avoids direct access to
the attribute, thus a new value can be assigned only
through the setter method that checks for conformance to
constraints.