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:
class Office { String id; String name; } class Person { String id; String name; } // we could use any string we want, even the ID from the office interface PersonService { Person getById(String id); }
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:
final class OfficeId { String value; } class Office { OfficeId id; String name; } final class PersonId { String value; } class Person { PersonId id; String name; } // we can now use the real type, compile time save interface PersonService { Person getById(PersonId id); }
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.
Advantages
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.
Disadvantages
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:
// with strong ID { id: {value: "abc"}, name: "Main Office"} // without strong id, or what you usually want { id: "abc", name: "Main Office"}
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.