Code Smell 50 - Object Keys

Maxi Contieri - Dec 12 '20 - - Dev Community

Primary keys, IDs, references. The first attribute we add to our objects. They don't exist in the real world.

Problems

Solutions

  1. Reference object to objects.

  2. Build a MAPPER.

  3. Only use keys if you need to provide an external (accidental) reference. Databases, APIs, Serializations.

  4. Use dark keys or GUIDs when possible.

  5. If you are afraid of getting a big relation graph use proxies or lazy loading.

  6. Don't use DTOs.

Sample Code

Wrong

Right

Detection

This is a design policy.

We can enforce business objects to warn us if we define an attribute or function including the sequence id.

Tags

  • Accidental

Conclusion

Ids are not necessary for OOP. You reference objects (essential) and never ids (accidental).

In case you need to provide a reference out of your system's scope (APIs, interfaces, Serializations) use dark and meaningless IDs (GUIDs).

Relations

More info

Credits

Photo by Maurice Williams on Unsplash


All problems in computer science can be solved by another level of indirection.

David Wheeler

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .