I’ve noticed, there’s really no rhyme or reason to whether my repositories take objects or primitives as parameters, or whether CREATE methods return just an int (ID from the DB) or the full-fledged object.
So my question is, should repositories pass around and return objects, or primitives? What advice can you give on this matter? Can you share any pitfalls or experiences with either approach?
Example:
public class ProductRepository : IProductRepository
{
// Pass in the whole object to the repo method...?
public int Add(Product product)
{
// return just the productId...?
}
// Pass in the individual primitive values...?
public Product Add(string productName, decimal productPrice, string description)
{
// return the whole Product object...?
}
}
What about if info is needed from multiple objects? Surely from an OOP standpoint it’s better to pass around objects here, no? (I’m being cheeky here…)
public int Add(int merchantId, Product product)
{
// database call needs merchant info...
}
public int Add(Merchant merchant, Product product)
{
var merchantId = merchant.ID;
// database call needs merchant info...
}
A repository and a factory are distinct concepts. A factory is responsible for creating objects; a repository is responsible for taking created-elsewhere objects and adding them to a data store.
From this perspective, a repository should not be responsible for creating objects, and thus has no reason to operate on primitive values.