...
This compliant solution demonstrates that the context in which code appears can impact its compliance. This example includes the same isName()
method as the previous noncompliant example, but as part of a more general method that tests string arguments.
Code Block | ||
---|---|---|
| ||
public class Foo {
private boolean isName(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 isName(s);
}
}
|
The isName()
method is a private method with only one caller in its containing class. The calling method, testString()
, guarantees that isName()
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.
...
...