Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Comparison of identical values

ID: java/comparison-of-identical-expressionsKind: problemSecurity severity: Severity: errorPrecision: very-highTags:   - quality   - reliability   - correctness   - logicQuery suites:   - java-code-quality.qls   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

If two identical expressions are compared (that is, checked for equality or inequality), this is typically an indication of a mistake, because the Boolean value of the comparison is always the same. Often, it indicates that the wrong qualifier has been used on a field access.

An exception applies to inequality (!=) and equality (==) tests of a floating point variable with itself: the special floating point valueNaN (”not-a-number”) is the only value that is not considered to be equal to itself. Thus, the testx!=x wherex is afloat ordouble variable is equivalent to checking whetherx isNaN, and similarly forx==x.

Recommendation

It is never good practice to compare a value with itself. If you require constant behavior, use the Boolean literalstrue andfalse, rather than encoding them obscurely as1==1 or similar.

If an inequality test (using!=) of a floating point variable with itself is intentional, it should be replaced byDouble.isNaN(...) orFloat.isNaN(...) for readability. Similarly, if an equality test (using==) of a floating point variable with itself is intentional, it should be replaced by!Double.isNaN(...) or!Float.isNaN(...).

Example

In the example below, the original version ofCustomer comparesid withid, which always returnstrue. The corrected version ofCustomer includes the missing qualifiero in the comparison ofid witho.id.

classCustomer{...publicbooleanequals(Objecto){if(o==null)returnfalse;if(Customer.class!=o.getClass())returnfalse;Customerother=(Customer)o;if(!name.equals(o.name))returnfalse;if(id!=id)returnfalse;// Comparison of identical valuesreturntrue;}}classCustomer{...publicbooleanequals(Objecto){if(o==null)returnfalse;if(Customer.class!=o.getClass())returnfalse;Customerother=(Customer)o;if(!name.equals(o.name))returnfalse;if(id!=o.id)returnfalse;// Comparison correctedreturntrue;}}

References


[8]ページ先頭

©2009-2025 Movatter.jp