Provide a type (and thus static type-checking) for values like IDs
IDs like customer id, contract id, etc. are mere integers or strings and get easily confused. This creates nasty bugs.
Create a wrapper around a string which holds the value. Then the compiler can do static type checking based on this wrapper class.
Have a wrapper class around a string, provide some conversion methods and override toString()
, as well as equals()
and hashCode()
.
public class CustomerId { private String value; public static CustomerId of(String value) { return new CustomerId(value); } public static CustomerId of(Integer value) { return new CustomerId(value.toString()); } public CustomerId(String value) { if (value == null) throw new IllegalArgumentException("value may not be null"); this.value = value; } public int asInt() throws NumberFormatException { return Integer.parseInt(value); } @Override public String toString() { return value; } @Override public boolean equals(Object that) { if (!that instanceof CustomerId) return false; return this.value.equals(((CustomerId) that).value); } @Override public int hashCode() { return value.hashCode(); } }
Discuss this wiki article and the pattern on the corresponding talk page.