Versions Compared

Key

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

Methods should always try 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 is consistent with the advice in EXP02-J. Do not ignore values returned by methods. The returned value should be as representative of the last known state as far as possible and should be designed keeping in mind the perceptions and mental model of the developer.

...

To gain better ability at telling apart correct from fallacious results and enforcing that the incorrect results be carefully handled, a combination of the aforementioned approaches is recommended. At the same time, there are cases when an error value should be returned instead of an exception and vice versa. For instance, if some method is capable of failing in a variety of different ways, it is better to return failure codes than endeavoring to throw scores of different exceptions. Note that no possible failure codes should be within the range of the valid return values.

Wiki Markup
Sometimes a state testing method \[[Bloch 08|AA. Java References#Bloch 08]\] can be used to ensure that the object is in consistent state at all points in time. This approach is not useful in the absence of external synchronization. Also, there is a TOCTOU race condition between invocation of the object's state testing method and the call to a method that depends on the itsobject's state. During this interval, the object's state could change surreptitiously.

...

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;
}

...

This solution combines the best of both worlds - exceptions and status codes. In this case, an exception is thrown if the operation is not successful. This ensures that the client has to handle the event wherein the Node is not found. If the Node is found, it is simply updated and returned.

Code Block
bgColor#CCCCFF
public Node updateNode(int id, int newValue) throws IdNotFoundException {
  Node current = root;
  while(current != null){
    if(current.getId() == id){
      current.setValue(newValue);
      return current;
    }
    current = current.next;
  }	
  throw new NodeNotFoundException();
}

...