# Code Smell 50 - Object Keys

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

> TL;DR: Reference objects with objects, not ids.   

# Problems

- Coupling

- Accidental Implementation

- [Bijection Principle](https://maximilianocontieri.com/the-one-and-only-software-design-principle) Violation.

# Solutions

1. Reference *object* to *objects*.

2. Build a [MAPPER](https://maximilianocontieri.com/what-is-wrong-with-software).

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

4. Use dark keys or [GUIDs](https://en.wikipedia.org/wiki/Universally_unique_identifier) when possible.

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

6. Don't use DTOs.

%[https://maximilianocontieri.com/code-smell-40-dtos]

# Sample Code

## Wrong

%[https://gist.github.com/mcsee/388923d775ca893eb1e6ca4c28c3287f]

## Right

%[https://gist.github.com/mcsee/9a0f4f02514f740f3872cbc463d25c8b]

# 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

%[https://maximilianocontieri.com/code-smell-20-premature-optimization]

# More info

%[https://maximilianocontieri.com/what-is-wrong-with-software]

%[https://maximilianocontieri.com/the-one-and-only-software-design-principle]

%[https://maximilianocontieri.com/coupling-the-one-and-only-software-design-problem]

# Credits

Photo by <a href="https://unsplash.com/@mauricew98">Maurice Williams</a> on <a href="https://unsplash.com/s/photos/keychain">Unsplash</a>

* * *

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

_David Wheeler_
 
* * *
 
%[https://mcsee.hashnode.dev/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://mcsee.hashnode.dev/how-to-find-the-stinky-parts-of-your-code]
