views:

71

answers:

2

After I've filled with data the query object, should there be an object that executes the query (filled query object as method parameter) or should the object execute the query by itself ?

+2  A: 

Something else should execute the query.

If not you're violating SRP as the query is encapsulating both the specification of the query and the execution of the query.

Think of how it's done in LINQ-to-SQL for example. In LINQ-to-SQL you can think of expression trees as representing query specifications and it's up to the LINQ-to-SQL provider to interpret the expression tree and convert it to SQL.

So it should be here. If you have the query object also execute the query then you've coupled the query specification to the specifics of where you are executing your query. Rather, they should be separate so that the query object can be reused in other contexts (query a database, query an in-memory collection, etc.). Again, this is how it is in LINQ. An expression tree can be used in LINQ-to-SQL, LINQ-to-objects and LINQ-to-XML with no change.

Jason
I was thinking similar.But Ayendes articles confused me http://ayende.com/Blog/archive/2007/03/29/Query-Objects-vs.-Methods-On-The-Repository.aspxHe is using a find method on his query object.
+1  A: 

The real question here is: Does the responsibility of how to query (and possibly enumerate) a data source belong to the Query Object?

The answer can often change between different frameworks/solutions, however to me at least, the Query Object should represents a specification of what the data you want should conform to. That is it's main responsibility.

It should not know how to touch the DB through whatever data API is available, rather it should be utilized by a Service/Component that understands how to map the Query Object to whatever backing store it being used.

This way you could potentially utilize different Data Sources with the same Query Object, as well as allow clients to create and pass Query specification objects to the server (could be better solution than having server methods with tons of parameters).

If one changed the data access mechanism (such as from raw SQL to Hibernate) nothing with the Query Objects would have to change if done this way (there could potentially be many different Query Objects)- only the objects responsible for mapping the Query Objects to actual queries would need to change

saret