Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: code example wordsmithing

...

Noncompliant Code Example

As shown in this example, noncompliant methods 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 gives no indication if it modified any node or not. A  method can silently corrupt the state of the object if they fail to return a value that the developer can intuitively interpret: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;
  }
}

...

This compliant solution returns the result of the operation: true for success  if it modified a node and false for failure 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;
}

...

This compliant solution returns the updated Node so that the developer can simply check for a null value lest if the operation fails. Return values for methods can vary depending on the control flow or the information that the developer finds more useful.

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

...

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

...