开发者

Should repositories use objects or primitives?

开发者 https://www.devze.com 2023-04-12 14:53 出处:网络
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

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 pro开发者_如何学PythonductName, 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...
}


normaly you will see after a short time (if you use multiple Repositories) that this is a pattern itself and can be refactored in some kind of Base-class (for the data-access). But in order to do this you won't be able to give the expanded parameters for Add/Update, etc. (and neither should you - just think of an object with 10+ properties) but just the pattern with the object itself.

So use option 1 ;)


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.


A repository works on entities, not primitive fields. The primitive fields are typically extracted from the entity by Data Access, one level of abstraction below the repository. Thus to answer your question, always use objects--your primitive fields are an implementation detail of the data access layer and have no business acting as parameters in a repository interface, unless they are part of a query filter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号