You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

According to [[Ware]], 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 value returned should be as more representative as possible and should consider the way the developer is going to handle it.

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.

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

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.

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

Compliant solution

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.

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

References

[[Ware 08]]

  • No labels