====== Type-Safe Wrapper ====== ===== Alternative Names ===== ===== Context ===== * [[contexts:Object-Oriented Design]] ===== Intent ===== Provide a type (and thus static type-checking) for values like IDs ===== Problem ===== IDs like customer id, contract id, etc. are mere integers or strings and get easily confused. This creates nasty bugs. ===== Solution ===== Create a wrapper around a string which holds the value. Then the compiler can do static type checking based on this wrapper class. ==== Structure ==== Have a wrapper class around a string, provide some conversion methods and override ''toString()'', as well as ''equals()'' and ''hashCode()''. ==== Dynamics ==== ==== Implementation Hints ==== * Don't allow null values to be wrapped. Either a variable is null or it has a value but having a wrapper around a null is confusing. ==== Variations ==== ===== Origin ===== ===== Advantages ===== /*reference principles here*/ * [[principles:Murphy's Law]] (ML): Static type checking makes certain bugs impossible ===== Disadvantages ===== /*reference principles here*/ * [[principles:More Is More Complex]] (MIMC): You have to write and maintain more code ===== Relations to Other Patterns ===== ==== Generalizations ==== * [[Value Object]] ==== Specializations ==== ==== Alternative Patterns ==== ==== Complementary Patterns ==== ==== Pattern Collections ==== ===== Examples ===== ==== Example 1: ==== 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(); } } ===== Description Status ===== /* Choose one of the following and comment out the rest: */ [[wiki:Stub]] /*[[wiki:Incomplete]]*/ /*[[wiki:Complete]]*/ ===== Further Reading ===== ===== Discussion ===== Discuss this wiki article and the pattern on the corresponding [[talk:patterns:Type-safe Wrapper|talk page]].