Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a guid as identity field better in domain-driven design?

Is it easier to implement domain-driven design when using guids as identity fields instead of auto incrementing integers? With guids you don't have to jump to the database to get the actual value.

like image 916
Lieven Cardoen Avatar asked Dec 01 '22 06:12

Lieven Cardoen


2 Answers

Well, GUIDs are easy and look like the best fit. They're tempting to frontend programmers, since they don't have to deal with the database.

On the other hand, when looking at the potential drawbacks they have when used without thinking about database issues too much, I would warn against them as much as possible.

The question really is: do you really need to know the ID of the entity before it's stored in the databsae? REALLY? WHY?

If you do decide to go with GUIDs in the end, and if you're using SQL Server as your database backend (I don't know enough about other RDBMS to make an informed suggestion), I would strongly recommend you make absolutely sure that the GUIDs are not being used as the clustering key on the tables. This will kill your performance - no doubt.

If you do use GUIDs as your primary key, make sure to use something else, some other column that wrecks less havoc on your database, as your clustering key instead - a INT IDENTITY would be my first choice.

Check out these articles by Kimberly Tripp on why a GUID is definitely not a good idea as a clustering key in a SQL Server database - she's the ultimate guru when it comes to indexing and performance issues with indexing and she can makes those points much better than I ever could:

  • GUIDs as PRIMARY KEYs and/or the clustering key
  • The Clustered Index Debate Continues...
  • Ever-increasing clustering key - the Clustered Index Debate..........again!

Marc

like image 153
marc_s Avatar answered Dec 05 '22 03:12

marc_s


One of the core tenets of DDD is Persistence Ignorance. So yes, GUIDs are the easiest way to provide your objects with unique identity without having to rely on a persistence store.

NB: If you're concerned about database performance using GUIDs, consider using COMBs (specifically for SQL Server index fragmentation)

like image 34
Vijay Patel Avatar answered Dec 05 '22 01:12

Vijay Patel