I like Martin Fowler’s FixedLengthString pattern idea, and I can’t help thinking implementation.

public final class FixedLengthString {
private int length;
private String value;

public FixedLengthString(int length) { this.length = length; }

public int getLength() { return length; }

public void setValue(String value) throws IllegalArgumentException {
if (value.length != length) throw new IllegalArgumentException(”text”);
this.value = value;
}

public String getValue() {
return value;
}
}

There is a couple of apparent drawbacks to this implementation:
- String creation is required
- It’s a Read/Write implementation
- Calling constructor+setString() seems a bit more akward (to say the least).

While improvements on my first cut are probably easy to find, an ideal solution
is most likely impossible on Sun’s Java platform.

Our only hope is that the Generics JSR brings in templating similar to that found
in C++. I can only imagine this kind of a implementation:

FixedLengthString ssn = new FixedLengthString(”123456789″);