Java Reference
In-Depth Information
and the call to a method that depends on the object's state. During this interval, the ob-
ject's state could change unexpectedly or even maliciously.
Methodreturnvaluesand/orerrorcodesmustaccuratelyspecifytheobject'sstateatan
appropriate level of abstraction. Clients must be able to rely on the value for performing
critical actions.
Noncompliant Code Example
The updateNode() method in this noncompliant code example modifies a node if it can
find it in a linked list and does nothing if the node is not found.
Click here to view code image
public void updateNode(int id, int newValue) {
Node current = root;
while (current != null) {
if (current.getId() == id) {
current.setValue(newValue);
break;
}
current = current.next;
}
}
Thismethodfailstoindicatewhetheritmodifiedanynode.Consequently,acallercan-
not determine that the method succeeded or failed silently.
Compliant Solution (Boolean)
This compliant solution returns the result of the operation as true if it modified a node
and false if it did not.
Click here to view code image
public boolean updateNode(int id, int newValue) {
Node current = root;
while (current != null) {
if (current.getId() == id) {
current.setValue(newValue);
return true; // Node successfully updated
}
current = current.next;
}
Search WWH ::




Custom Search