Object-oriented – Should an object know its own ID

object-orientedobject-oriented-design

obj.id seems fairly common and also seems to fall within the range of something an object could know about itself. I find myself asking why should my object know its own id?

It doesn't seem to have a reason to have it? One of the main reason for it existing is retrieve it, and so my repositories need to know it, and thus use it for database interaction.

I also once encountered a problem where I wanted to serialize an object to JSON for a RESTful API where the id did not seem to fit in the payload, but only the URI and including it in the object made that more difficult.

Should an object know it's own id? why or why not?

update:
Terms

  1. id: Identifier attribute on an object. in database terms, a surrogate key not a natural key.
  2. Object: an Entity, or otherwise uniquely identifiable object within the system.

Best Answer

It's fairly common to include the ID, but it's also common to use dictionaries, i.e. the data structures where each object is associated with its ID in a way that you can easily retrieve this object knowing the corresponding ID, but the object doesn't know it.

For example, if you're creating an API with two methods:

Then you don't need to resend the ID 452 in the JSON response of the second request. The user of the API already knows the ID.