Should an object know its own ID?

Posted by xenoterracide on Programmers See other posts from Programmers or by xenoterracide
Published on 2012-09-29T20:35:39Z Indexed on 2012/09/29 21:49 UTC
Read the original article Hit count: 239

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?

© Programmers or respective owner

Related posts about object-oriented

Related posts about object-oriented-design