User Tools

Site Tools


patterns:type-safe_wrapper

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

  • 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

  • Murphy's Law (ML): Static type checking makes certain bugs impossible

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

Further Reading

Discussion

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

patterns/type-safe_wrapper.txt · Last modified: 2017-05-29 14:08 by christian