Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fooled around with second nce/cs pair

...

This noncompliant code example defines an isNameisProperName() method that takes a that returns true of the specified String argument and returns true if the given string is a valid name . A valid name is defined as (two capitalized words separated by one or more spaces).

Code Block
bgColor#FFcccc
public boolean isNameisProperName(String s) {
  String names[] = s.split(" ");
  if (names.length != 2) {
    return false;
  }
  return (isCapitalized(names[0]) && isCapitalized(names[1]));
}

Method isNameisProperName() is noncompliant because it may be called with a null argument results in isName() dereferencing , resulting in a null pointer dereference.

Compliant Solution

This compliant solution demonstrates that the context in which code appears can impact its compliance. This example includes the same isNameisProperName() method implementation as the previous noncompliant example, but as part of a more general method that tests string arguments. is now a private method with only one caller in its containing class.  

Code Block
bgColor#ccccff
public class Foo {
  private boolean isNameisProperName(String s) {
    String names[] = s.split(" ");
    if (names.length != 2) {
      return false;
    }
    return (isCapitalized(names[0]) && isCapitalized(names[1]));
  }

  public boolean testString(String s) {
    if (s == null) return false;
    else return isNameisProperName(s);
  }
}


The isName() method is a private method with only one caller in its containing class. The calling method, testString(), guarantees that isNameisProperName() is always called with a valid string reference. As a result, the class conforms with this rule, even though isName() in isolation does not. In general, guarantees of this sort can be used to eliminate null pointer dereferences.

...