Some classes filled by frameworks (like beans). So you can't guaranty that all fields set.
Look to example: classes marked as @Entity
usually have Integer id
field. hashCode
can be written as:
public int hashCode() {
return id.hashCode();
}
but defensive code may look like:
public int hashCode() {
return (id != null) ? id.hashCode() : 0;
}
Do I need write checks for null or surround code with try { ... } catch (Exception e)
in hashCode
and equals
functions?
I have no arguments for defencive coding is such case because it hide putting inconsistent objects to collections and lead to late errors. Am I wrong in this position?
UPDATE I wrote such code:
import java.util.*;
class ExceptionInHashcode {
String name;
ExceptionInHashcode() { }
ExceptionInHashcode(String name) { this.name = name; }
public int hashCode() {
// throw new IllegalStateException("xxx");
return this.name.hashCode();
}
public static void main(String args[]) {
Hashtable list = new Hashtable();
list.put(new ExceptionInHashcode("ok"), 1);
list.put(new ExceptionInHashcode(), 2); // fail
System.out.println("list.size(): " + list.size());
}
}
and run it:
java -classpath . ExceptionInHashcode
Exception in thread "main" java.lang.NullPointerException
at ExceptionInHashcode.hashCode(ExceptionInHashcode.java:12)
at java.util.Hashtable.hash(Hashtable.java:262)
at java.util.Hashtable.put(Hashtable.java:547)
at ExceptionInHashcode.main(ExceptionInHashcode.java:18)
I think that I can find error early instead of returning zero if object is in wrong state...