Versions Compared

Key

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

...

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

As shown in this noncompliant code example, a method modifies a node if it can find it in a linked list and does nothing if the node is not in the list. But this method fails to indicate whether it modified any node. A method can silently corrupt the state of the object if it provides little communication describing what it did.

Code Block
bgColor#FFCCCC
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 (boolean)

This compliant solution returns the result of the operation: true if it modified a node and false otherwise:

Code Block
bgColor#CCCCFF
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 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
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 new NodeNotFoundException();
}

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. Return values for methods can vary depending on the control flow or the information that the developer finds more useful.

...

 A return value that might be null is an in-band error indicator, which is discussed more thoroughly in 52. ERR52-JG. 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

...