When a variable is assigned a value after checking if it's not null
(for example, x != null
), it might be inadvertently overwritten. We recommend that you verify a variable is null
(for example, x == null
) before assigning it a value.
1public void nullCheckNoncompliant() {
2 if (data1 != null) {
3 // Noncompliant: overwriting immediately after a non-null check is likely to be a typo.
4 data1 = data2;
5 }
6}
1public void nullCheckCompliant() {
2 if (data1 == null) {
3 // Compliant: overwriting after a null check is a common pattern.
4 data1 = data2;
5 }
6}