Comparison Using Wrong Factors

Incomplete Base
Structure: Simple
Description

This weakness occurs when a program compares two items but checks the wrong properties or attributes. This flawed comparison leads to incorrect decisions, creating security and logic errors.

Extended Description

At its core, this bug happens because the comparison logic doesn't align with the developer's actual intent. For instance, you might intend to compare the data inside two objects, but the code accidentally compares their memory addresses instead. This causes two objects with identical content to be seen as different, breaking the program's expected flow. To prevent this, always verify that your comparison operators or custom equality methods are evaluating the correct, relevant characteristics. In object-oriented languages, this often means overriding the standard equality method to compare internal state, not object references. For primitive data, ensure you're not mistakenly comparing metadata (like string lengths as a proxy for content) instead of the values themselves.

Common Consequences 1
Scope: Other

Impact: Varies by Context

Potential Mitigations 1
Phase: Testing
Thoroughly test the comparison scheme before deploying code into production. Perform positive testing as well as negative testing.
Demonstrative Examples 1

ID : DX-60

In the example below, two Java String objects are declared and initialized with the same string values. An if statement is used to determine if the strings are equivalent.

Code Example:

Bad
Java
java
However, the if statement will not be executed as the strings are compared using the "==" operator. For Java objects, such as String objects, the "==" operator compares object references, not object values. While the two String objects above contain the same string values, they refer to different object references, so the System.out.println statement will not be executed. To compare object values, the previous code could be modified to use the equals method:

Code Example:

Good
Java
java
Applicable Platforms
Languages:
Not Language-Specific : Undetermined
Modes of Introduction
Implementation
Related Weaknesses