Strong IDs

In some projects you may encounter the so called „strong id pattern“.

What is it?

Strong IDs are simply wrapped primitive or simple types into classes. Just remember what we did in Java before the Enum come around. We had just Strings or Numbers in the code which we used to assign well known values to specific objects. In some projects these Strings has already been wrapped into classes. Now with Enums this is mostly obsolete. But for Ids we can still apply this pattern.

Imagine the following classes:

Both classes have an id, simply just as a String. Keeping just these ids in hand you cannot tell if it is a Person Id or the Office Id. To make it more obvious we could change the code too:

If you now have either the OfficeId or PersonId in hand, you cannot accidentally mix them up. You exactly know what you have and what it identifies.

Usually the ID classes are not mutable too.


In larger projects you have many classes, it is easier to understand and keep different IDs in method signatures. That we use the right type in generic lists or method calls can be ensured now during compile time.

Also nice we can easyer change the type of ID, e.g. from String to Long or to a composite type.

If we move this sample to REST where we usually want to return a URI as an identifier to an object this pattern even gets more attractive. If we assume our IDs have been initially just simple Longs wrapped into a Strong ID we could change the value it a String and create URI / String which we return to the clients.


Well no pro without a contra. Having strong ids in the system makes the handling sometimes awkward. E.g. if you serialize this to JSON you get:

Furthermore Hibernate nor simple bean serializer/ deserializer can handle well immutable classes. Overall we would need to add additional code to handle that. e.g. Hibernate custom types etc.

Paul Sterl has written 20 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">