...
Alternatively, an object can provide a state-testing method [Bloch 2008] that checks whether the object is in a consistent state. This approach is useful only in cases where the object's state cannot be modified by external threads. This prevents a time-of-check, time-of-use (TOCTOU) race condition between invocation of the object's state-testing method and the call to a method that depends on the object's state. During this interval, the object's state could change unexpectedly or even maliciously.
Method return values and/or error codes must accurately specify the object's state at an appropriate level of abstraction. Clients must be able to rely on the value for performing critical decisions.
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.
...
This method fails to indicate whether it modified any node. Consequently, a caller cannot 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.
Code Block | ||
---|---|---|
| ||
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; } return false; } |
Compliant Solution (Exception)
This compliant solution returns the modified Node
when one is found and throws a NodeNotFoundException
when the node is not available in the list.
...
Using exceptions to indicate failure can be a good design choice, but throwing exceptions is not always appropriate. In general, a method should throw an exception only when it is expected to succeed but an unrecoverable situation occurs or when it expects a method higher up in the call hierarchy to initiate recovery.
Compliant Solution (Null Return Value)
This compliant solution returns the updated Node
so that the developer can simply check for a null
value if the operation fails.
...
A return value that might be null is an in-band error indicator, which is discussed more thoroughly in ERR52-J. Avoid in-band error indicators. This design is permitted but is considered inferior to other designs, such as those shown in the other compliant solutions in this guideline.
Applicability
Failure to provide appropriate feedback through a combination of return values, error codes, and exceptions can lead to inconsistent object state and unexpected program behavior.
Bibliography
[Bloch 2008] | Item 59, "Avoid unnecessary use of checked exceptions" |
[Ware 2008] | Writing Secure Java Code |
...