Rule Definition
Whenever you work with objects in detached state, and especially if you test them for equality (usually in hash-based collections), you need to supply your own implementation of the equals() and hashCode() methods for your persistent classes.
Nevertheless, it's possible to build a complex application with identity (default) equals as long as you exercise discipline when dealing with detached objects from different sessions. If this concept of equality isn't what you want, you must override equals() in your persistent classes.
Remediation
Check if you have instances from multiple sessions and implement Object.GetHashCode and Object.Equals if it is the case. If it is not the case, we recommend implementing it anyway to avoid issues during future evolutions.
Violation Code Sample
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
Fixed Code Sample
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
public override int GetHashCode()
{
return n1;
}
public override bool Equals(Object obj)
{
if (obj == null || !(obj is MyObject))
return false;
else
return n1 == ((MyObject)obj).n1;
}
}
Related Technologies
Technical Criterion
CWE-1097 - Persistent Storable Data Element without Associated Comparison Control Element
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.