Take this simple Groovy class:
public class TestClass {
String s
}
Hitting ‘autogenerate equals and hashCode’ a popular IDE generates the following code:
public class TestClass {
String s
boolean equals(o) {
if (this.is(o)) return true;
if (!o || getClass() != o.class) return false;
TestClass testClass = (TestClass) o;
if (s ? !s.equals(testClass.s) : testClass.s != null) return false;
return true;
}
int hashCode() {
return (s ? s.hashCode() : 0);
}
}
At first this looks unusual but ok, but taking a closer look there is a bug in there, can you spot it? And even better: write a test for it?
Lessons learned:
- If something looks suspicious write a test for it.
- Question your assumptions. There is no assumption which is safe from be in question.
- Don’t try to be too clever.