Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki MarkupAccording to \[[Ware|AA. Java References#Ware 08]\], methods should always return a value that allows the developer to know the current state of the object and/or the result of the operation. This is consistent with what is stated in EXP02-J. Do not ignore values returned by methods. The returned value should be as more representative as possible and should consider the way the developer is going to handle itMethods should be designed to return a value that allows the developer to learn about the current state of the object and/or the result of an operation. This advice is consistent with EXP00-J. Do not ignore values returned by methods. The returned value should be representative of the last known state and should be chosen keeping in mind the perceptions and mental model of the developer.

Feedback can also be provided by throwing either standard or custom exception objects derived from the Exception class. With this approach, the developer can still get precise information about the outcome of the method and proceed to take the necessary actions. To do so, the exception thrown should give provide a good description of the problem found in execution.

To achieve a better handling of both correct and incorrect results, a combination of the two previous approaches should be used. Be aware to differentiate between cases when an error value should be returned instead of an exception and vice versa.

Noncompliant code example

As shown in this example, methods that are subject to fail could compromise the state of the object if they do not return a value that the developer can interpret.

detailed account of the abnormal condition at the appropriate abstraction level.

APIs should use a combination of these approaches both to help clients distinguish correct results from incorrect ones and to encourage careful handling of any incorrect results. In cases where there is a commonly accepted error value that cannot be misinterpreted as a valid return value for the method, that error value should be returned; and in other cases, an exception should be thrown. A method must not return a value that can hold both valid return data and an error code; see ERR52-J. Avoid in-band error indicators for more details.

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. 

Code Block
bgColor#FFCCCC
Code Block
bgColor#F7D6C1

public void updateNode(int id, int newValue) {
		
  Node current = root;
  while (current != null) {
    if (current.getId() == id) {
      current.setValue(newValue);
      break;
    }
    current = current.next;
  }
}

Compliant solution

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 A recommended solution for this example could be to return the result of the operation . The method could return true if it was successful and false if it wasn't.as true if it modified a node and false if it did not.

Code Block
bgColor#CCCCFF
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

...

Another solution that could provide more information could return the updated node so the developer could verify the new state of the object and null if the operation did not succeed. Appropriate return values for methods could vary depending on the different paths that the implementation can follow or on the information that the developer finds more useful.

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.

Code Block
bgColor#CCCCFF
Code Block

public Node updateNode(int id, int newValue){
	 
    throws NodeNotFoundException {
  Node current = root;
  while (current != null) {
    if (current.getId() == id) {
      current.setValue(newValue);
      return current;
    }
    current = current.next;
  }	
  throw returnnew nullNodeNotFoundException();
}

Compliant solution

This solution provides a combination of both approaches mentioned. In this case, an exception is thrown if the received newValue is not evaluated as a valid ID. The code then follows the same behavior as in the previous compliant solution, returning the updated Node if it was found and null otherwise.

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. 

Code Block
bgColor#CCCCFF
Code Block

public Node updateNode(int id, int newValue){
  if(isInvalidId(newValue)){{	
    throw new InvalidIdException();
  }
  Node current = root;
  while (current != null) {
    if (current.getId() == id) {
      current.setValue(newValue);
      return current;
    }
    current = current.next;
  }
  return null;
}

References

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

 

...

Image Added Image Added Image Added Wiki Markup\[[Ware 08|AA. Java References#Ware 08]\]