Does command/query separation apply to a method that creates an object and returns its ID?
Posted
by
Gilles
on Programmers
See other posts from Programmers
or by Gilles
Published on 2011-12-12T17:53:38Z
Indexed on
2012/11/14
23:18 UTC
Read the original article
Hit count: 364
object-oriented
|cqrs
Let's pretend we have a service that calls a business process. This process will call on the data layer to create an object of type A in the database.
Afterwards we need to call again on another class of the data layer to create an instance of type B in the database. We need to pass some information about A for a foreign key.
In the first method we create an object (modify state) and return it's ID (query) in a single method.
In the second method we have two methods, one (createA) for the save and the other (getId) for the query.
public void FirstMethod(Info info)
{
var id = firstRepository.createA(info);
secondRepository.createB(id);
}
public void SecondMethod(Info info)
{
firstRepository.createA(info);
var key = firstRepository.getID(info);
secondRepository.createB(key);
}
From my understanding the second method follows command query separation more fully. But I find it wasteful and counter-intuitive to query the database to get the object we have just created.
How do you reconcile CQS with such a scenario?
Does only the second method follow CQS and if so is it preferable to use it in this case?
© Programmers or respective owner