Table of Contents

Type-Safe Wrapper

Alternative Names

Context

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

Variations

Origin

Advantages

Disadvantages

Relations to Other Patterns

Generalizations

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

Stub

Further Reading

Discussion

Discuss this wiki article and the pattern on the corresponding talk page.