Question
This question was originally to find out if anyone knows of a way to modify the Eclipse equals() and hashCode() templates to generate the following pattern for Strings (making null equivalent to "").
if ([value] == null || [value].length() == 0) {
if (other.[value] != null && other.[value].length() > 0) {
return false;
}
} else if (![value].equals(other.[value])) {
return false;
}
One suggested solution
A lot of answers have suggested normalizing input in the setters (either converting all empty strings to nulls, or nulls to empty strings). I find that dangerous. Here are two legitimate pieces of code that will crash the program if the user isn't aware of this side effect.
If all empty strings are made nulls, this will crash:
myObject.setName("");
String uppercaseName = myObject.getName().toUpperCase();
If all nulls are made empty strings, this will crash (debated advisability of this aside, I would generally expect it to work):
myObject.setName(myStringSubclassInstance);
MyStringSubclass string = myObject.getName().someCustomSubclassMethod();
If I went down this path, I would make the setters throw an InvalidArgumentException and spell that out in the documentation. That's the right way IMHO.
Better Solution
Ultimately, I don't think any of the recommended solutions were appropriate. This is not so much their fault, as it is the fault of the original question. After considering the feedback, I agree that the original question was predicated upon an inadvisable solution. I can't delete it though, so I've edited it to avoid misleading others.
What I decided to go with was utilizing the Builder Pattern to normalize values in the build() method. This results in objects that always have either null or empty Strings, but without adding side effects to setters or the equals() method.