Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Domain Driven Design Auto Incremented Entity Key

Just starting with Domain Driven Design and I've learned that you should keep your model in a valid state and when creating a new instance of a class it's recomended to put all required attributes as constructor parameters.

But, when working with auto incremented keys I just have this new ID when I call an Add method from my persistent layer. If I instanciate my objects without a key, I think they will be in a invalid state because they need some sort of unique identifier.

How should I implement my architecture in order to have my IDs before creating a new instance of my entity ?

like image 944
gsonego Avatar asked Dec 16 '15 15:12

gsonego


People also ask

Should I use auto increment ID?

Auto-increment should be used as a unique key when no unique key already exists about the items you are modelling. So for Elements you could use the Atomic Number or Books the ISBN number.

Should domain entities have ids?

Ids in domain entities is a design smell. In most cases, they indicate poor entity encapsulation. If you want proper separation of concerns, you should reduce the number of Ids in your domain entities to as low as possible. Heavy Ids usage is common for anemic model.

What is entity in domain driven design?

Domain-driven design recognizes multiple kinds of models. For example, an entity is an object defined not by its attributes, but its identity. As an example, most airlines assign a unique number to seats on every flight: this is the seat's identity.


1 Answers

Generated Random IDs

The pragmatic approach here is to use random IDs and generate them before instantiating an entity, e.g. in a factory. GUIDs are a common choice.

And before you ask: No, you won't run out of GUIDs :-)

Sequential IDs with ID reservation

If you must use a sequential ID for some reason, then you still have options:

  • Query a sequence on the DB to get the next ID. This depends on your DB product, Oracle for example has them).
  • Create a table with an auto-increment key that you use only as key reservation table. To get an ID, insert a row into that table - the generated key is now reserved for you, so you can use it as ID for the entity.

Note that both approaches for sequential IDs require a DB round-trip before you even start creating the entity. This is why the random IDs are usually simpler. So if you can, use random IDs.

DB-generated IDs

Another possibility is to just live with the fact that you don't have the ID at creation time, but only when the insert operation on the DB succeeds. In my experience, this makes entity creation awkward to use, so I avoid it. But for very simple cases, it may be a valid approach.

like image 186
theDmi Avatar answered Nov 13 '22 03:11

theDmi