Thursday, March 3, 2011

How to implement "Last 20 something" property in your domain class?

Let's say I need to implement domain model for StackOverflow.

If I am doing ORM, how can I define (and map) property for fetching "last comments" and other "last" things? It looks to me like this should be reflected in the domain model.

Sometimes I might need "all comments" though...

From stackoverflow
  • I might be influenced by my ORM tool but I see this as a query rather than a domain property. The domain contains the associations, and the repository encapsulates queries such as the one you are describing.

    badbadboy : So you would have one property "comments", and depending on which service layer method you call (GetAllComments or GetLastComments) you would get different sets of data inside?
    Cristian Libardo : Prett much. The entity would have a comments list that is lazy-loaded by the orm. On my repository I could have GetLastComment that takes the entity as a parameter and performs a (hql) query on the database to get the comments.
  • You would query your repository for the last comments by a specific user. something like

    IList<Comment> recentComments = repository.GetRecentComments(user,20);
    

    You COULD do this in the model, but depending on how many comments you expect to have I'd avoid it. The model shouldn't know how to populate itself, that is the job of the repository; however, if you're using something like NHibernate it will be there.

    public class User{
    
     public IList<Comment> Comments { get;set;}
    
     public IList<Comment> GetRecentComments()
     {
       // Logic
     }
    
    
    }
    

    In that implementation you're always going to load ALL the comments to get the last 20. Not a big deal if there are only 50 comments, but if there are 5,000 comments you've got quite a bit of overhead.

0 comments:

Post a Comment