How to apply version control on Domain Objects

487 views Asked by At

I have come to understand that with domain driven design, the domain objects do not persist in my application, but are rather created and dropped on demand.

I am thinking this might possibly lead to a new situation for my application where I now have to consider the version of the domain object I am dealing with.

In my old days I would update i.e. the username there and then, now I am however fetching and storing the whole user as an object after doing something with it, and I fear there is a risk of overwriting changes that another user made to that same object.

What is the correct way of dealing with this issue? A simple version field in the database? How would you then deal with the situation where the user is attempting an overwrite?

As I write this I realize I probably had similar issues with my old application, but I somehow feel it is more of an issue when dealing with domain objects...

2

There are 2 answers

0
Martin Podval On BEST ANSWER

There are two options how you can achieve updates, see Optimistic vs. Pessimistic locking

You probably talk about optimistic locking which achieve updates using version number. The principal is simple: your update just hope to some other thread/user do not update same (database) row. Query must contain version which match (or not) targeted database row.

This approach increases application (database) throughput as your second possible option - pessimistic locking - locks this row in database which just stop other thread/client until the transaction is committed.

0
Cerad On

Since this question was tagged with php then I'll assume it's not specific to DDD. The question also deals with concurrency issues at the database level.

You can add a version number column to your database table. Perform your updates with:

UPDATE user 
    SET name = 'Some new name', version = version + 1 
    WHERE id = 24 AND version = 42;

The 42 of course comes from whatever version the user had when you queried the record. The insert will only succeed if the version number has not been changed by some other request. You just need to check the update count and toss an exception if the count is 0.

This is a common implementation of what is known as optimistic locking.

Some PHP Orm systems such as Doctrine 2 have this built in: http://docs.doctrine-project.org/en/latest/reference/transactions-and-concurrency.html

And again I want to emphasize that this is a data persistence issue and not DDD. I rather doubt if you would make use of this version property at the domain model level.