Created
April 15, 2009 15:22
-
-
Save davetron5000/95841 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Immutable name */ | |
public class DefensiveName { | |
private String first; | |
private String last; | |
public DefensiveName(String first, String last) { | |
if (first == null) throw new IllegalArgumentException("first may not be null"); | |
if (last == null) throw new IllegalArgumentException("last may not be null"); | |
this.first = first; | |
this.last = last; | |
} | |
public String getFirst() { return first; } | |
public String getLast() { return last; } | |
public String toString() { return first + " " + last; } | |
public boolean equals(Object o) { | |
if (o == null) return false; | |
if (!o.getClass().equals(getClass()) return false; | |
DefensiveName other = (DefensiveName)o; | |
return getFirst().equals(other.getFirst()) && | |
getLast().equals(other.getLast()); | |
} | |
public int hashCode() { | |
return getFirst().hashCode() + getLast().hashCode(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Immutable name */ | |
public class OffensiveName { | |
private String first; | |
private String last; | |
public OffensiveName(String first, String last) { | |
if (first == null) throw new IllegalArgumentException("first may not be null"); | |
if (last == null) throw new IllegalArgumentException("last may not be null"); | |
this.first = first; | |
this.last = last; | |
} | |
public String getFirst() { return first; } | |
public String getLast() { return last; } | |
public String toString() { | |
return (getFirst() == null ? "" : getFirst()) + " " | |
+ (getLast() == null ? "" : getLast()); | |
} | |
public boolean equals(Object o) { | |
if (o == null) return false; | |
if (!o.getClass().equals(getClass()) return false; | |
DefensiveName other = (DefensiveName)o; | |
boolean firstEqual = getFirst() == null ? getFirst() == other.getFirst() : getFirst().equals(other.getFirst()); | |
boolean lastEqual = getLast() == null ? getLast() == other.getLast() : getLast().equals(other.getLast()); | |
return firstEqual && lastEqual | |
} | |
public int hashCode() { | |
return (getFirst() == null ? 0 : getFirst().hashCode() ) | |
+ getLast() == null ? 0 : getLast().hashCode()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment