Versions Compared

Key

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

Wiki Markup
According 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 returned should be as more representative as possible and should consider the way the developer is going to handle it.

Feedback can also be provided by throwing objects derived from the Exception class. With this approach, the developer can still get precise information about the outcome of the method. To do so, the exception thrown should give 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

...

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

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.

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

...