4

I want to be able to specify a typed interface which can be used with queries. I ultimately want to be able to do something like:

var query = _queryfactory.Create<IActiveUsersQuery>();
var result = query.Execute(new ActiveUsersParameters("a", "b"));
foreach (var user in result)
{
    Console.WriteLine(user.FirstName);
}

Looks simple enough, ehh? Notice that the query got typed parameters and a typed result. To be able to restrict the query factory to only contain queries we'll have to specify something like:

public interface IQuery<in TParameters, out TResult>
    where TResult : class
    where TParameters : class
{
    TResult Invoke(TParameters parameters);
}

But that's going to spread like cancer:

// this was easy
public interface IActiveUsersQuery : IQuery<ActiveUsersParameters, UserResult>
{

}

//but the factory got to have those restrictions too:
public class QueryFactory
{
    public void Register<TQuery, TParameters, TResult>(Func<TQuery> factory)
        where TQuery : IQuery<TParameters, TResult>
        where TParameters : class
        where TResult : class
    {
    }

    public TQuery Create<TQuery, TParameters, TResult>()
        where TQuery : IQuery<TParameters, TResult>
        where TParameters : class
        where TResult : class
    {
    }
}

Which ultimately leads to a factory invocation like:

factory.Create<IActiveUsersQuery, ActiveUsersParameters, UserResult>();

Not very nice since the user have to specify the parameter type and the result type.

Am I trying to control it too much? Should I just create a dummy interface:

public interface IQuery
{

}

to show the intent and then let the users create whatever they like (since they, and not the factory, will invoke the correct query).

However, the last option isn't very nice since it won't let me decorate queries (for instance dynamically cache them by using a caching decorator).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • Do you really need generic IQuery? IMO interfaces used as "method specifiers" instead of "common methods" is bad practice and might result in this kind of problems. The dummy interface is much better. – Euphoric Oct 10 '12 at 05:55
  • @Euphoric: If possible, I do want the generic query. Being able to decorate the queries will result in quite powerful features. – jgauffin Oct 10 '12 at 05:57
  • What do you mean "decorate the queries"? Also, note that because of this, you need to create at least one more class for input parameters. This wont be problem if you let concrete query do it's own implementation of Execute. – Euphoric Oct 10 '12 at 05:59
  • a) I mean using the decorator pattern inside the query factory. b) Are you referring to the `ActiveUsersParameters`? Yeah, its another class. Each query will have an interface, a result class, a parameters class and an implementation. That's quite SOLID ;) – jgauffin Oct 10 '12 at 06:02
  • I wouldnt' be so sure about "S". You have 4 different constructs for single thing : Pull data from DB. And data classes have no "responsibility". They just store data. – Euphoric Oct 10 '12 at 06:04
  • SOLID: ***SRP***: Each class have it's own responsibility. ***Open/Closed***: Each query can be extended (for instance inherit the parameter class to add support for additional parameters) ***LSP*** I can execute each query by using it's base interface **ISP** Small well defined interface ***DIP*** I'm depending on abstractions and not concretes. That's SOLID. – jgauffin Oct 10 '12 at 06:07
  • I will stop arguing with you here, but you should really reconsider doing this. You will have dozens, maybe thousands of queries in you system. This is really not good place to argue with SOLID. And SRP can be also read other way "One responsibility should be in single class." – Euphoric Oct 10 '12 at 06:09
  • There will not be thousands of queries. Each query is specific for a use case. Read the following article and you'll understand: http://blog.gauffin.org/2012/10/writing-decoupled-and-scalable-applications-2/ – jgauffin Oct 10 '12 at 06:13
  • Related: http://stackoverflow.com/questions/8511066/why-doesnt-c-sharp-infer-my-generic-types – Steven Oct 10 '12 at 06:31
  • @Euphoric: JGauffin is right here, but it's hard to discuss this here in the comments. [This article](http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92) describes the rational behind this. – Steven Oct 10 '12 at 06:34
  • @Steven: add your solution as an answer (from your query side blog post) – jgauffin Oct 10 '12 at 07:53

3 Answers3

5

I completely understand what you are trying to do here. You are applying the SOLID principles, so query implementations are abstracted away from the consumer, who merely sends a message (DTO) and gets a result. By implementing a generic interface for the query, we can wrap implementations with a decorator, which allows all sorts of interesting behavior, such as transactional behavior, auditing, performance monitoring, caching, etc, etc.

The way to do this is to define the following interface for a messsage (the query definition):

public interface IQuery<TResult> { }

And define the following interface for the implemenation:

public interface IQueryHandler<TQuery, TResult>
    where TQuery : IQuery<TResult>
{
    TResult Handle(TQuery query);
}

The IQuery<TResult> is some sort of marker interface, but this allows us to define statically what a query returns, for instance:

public class FindUsersBySearchTextQuery : IQuery<User[]>
{
    public string SearchText { get; set; }

    public bool IncludeInactiveUsers { get; set; }
}

An implementation can be defined as follows:

public class FindUsersBySearchTextQueryHandler
    : IQueryHandler<FindUsersBySearchTextQuery, User[]>
{
    private readonly IUnitOfWork db;

    public FindUsersBySearchTextQueryHandler(IUnitOfWork db)
    {
        this.db = db;
    }

    public User[] Handle(FindUsersBySearchTextQuery query)
    {
        // example
        return (
            from user in this.db.Users
            where user.Name.Contains(query.SearchText)
            where user.IsActive || query.IncludeInactiveUsers
            select user)
            .ToArray();
    }
}

Consumers can no take a dependency on the IQueryHandler<TQuery, TResult> to execute queries:

public class UserController : Controller
{
    IQueryHandler<FindUsersBySearchTextQuery, User[]> handler;

    public UserController(
        IQueryHandler<FindUsersBySearchTextQuery, User[]> handler)
    {
        this. handler = handler;
    }

    public View SearchUsers(string searchString)
    {
        var query = new FindUsersBySearchTextQuery
        {
            SearchText = searchString,
            IncludeInactiveUsers = false
        };

        User[] users = this.handler.Handle(query);

        return this.View(users);
    }
}

This allows you to add cross-cutting concerns to query handlers, without consumers to know this and this gives you complete compile time support.

The biggest downside of this approach (IMO) however, is that you'll easily end up with big constructors, since you'll often need to execute multiple queries, (without really violating the SRP).

To solve this, you can introduce an abstraction between the consumers and the IQueryHandler<TQuery, TResult> interface:

public interface IQueryProcessor
{
    TResult Execute<TResult>(IQuery<TResult> query);
}

Instread of injecting multiple IQueryHandler<TQuery, TResult> implementations, you can inject one IQueryProcessor. Now the consumer will look like this:

public class UserController : Controller
{
    private IQueryProcessor queryProcessor;

    public UserController(IQueryProcessor queryProcessor)
    {
        this.queryProcessor = queryProcessor;
    }

    public View SearchUsers(string searchString)
    {
        var query = new FindUsersBySearchTextQuery
        {
            SearchText = searchString
        };

        // Note how we omit the generic type argument,
        // but still have type safety.
        User[] users = this.queryProcessor.Execute(query);

        return this.View(users);
    }
}

The IQueryProcessor implementation can look like this:

sealed class QueryProcessor : IQueryProcessor
{
    private readonly Container container;

    public QueryProcessor(Container container)
    {
        this.container = container;
    }

    [DebuggerStepThrough]
    public TResult Execute<TResult>(IQuery<TResult> query)
    {
        var handlerType = typeof(IQueryHandler<,>)
            .MakeGenericType(query.GetType(), typeof(TResult));

        dynamic handler = container.GetInstance(handlerType);

        return handler.Handle((dynamic)query);
    }
}

It depends on the container (it is part of the composition root) and uses dynamic typing (C# 4.0) to execute the queries.

This IQueryProcessor is effectively your QueryFactory.

There are downsides of using this IQueryProcessor abstraction though. For instance, you miss the possibility to let your DI container verify whether a requested IQueryHandler<TQuery, TResult> implementation exists. You'll find out at the moment that you call processor.Execute instead when requesting a root object. You can solve this by writing an extra integration test that checks if an IQueryHandler<TQuery, TResult> is registered for each class that implements IQuery<TResult>. Another downside is that the dependencies are less clear (the IQueryProcessor is some sort of ambient context) and this makes unit testing a bit harder. For instance, your unit tests will still compile when a consumer runs a new type of query.

You can find more information about this design in this blog post: Meanwhile… on the query side of my architecture.

Steven
  • 166,672
  • 24
  • 332
  • 435
2

Do you really need TQuery in your factory? Could you not just use:

public void Register<TParameters, TResult>
        (Func<IQuery<TParameters, TResult>> factory)
    where TParameters : class
    where TResult : class
{
}

public IQuery<TParameters, TResult> Create<TParameters, TResult>()
    where TParameters : class
    where TResult : class
{
}

At that point, you've still got two type arguments, but assuming you'd usually want to fetch the query and immediately execute it, you could use type inference to allow something like:

public QueryExecutor<TResult> GetExecutor() where TResult : class
{
}

which would then have a generic method:

public IQueryable<TResult> Execute<TParameters>(TParameters parameters)
    where TParameters : class
{
}

So your original code would just become:

var query = _queryfactory.GetExecutor<UserResult>()
                         .Execute(new ActiveUsersParameters("a", "b"));

I don't know whether that will help in your actual case, but it's at least an option to consider.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

I might be OT, but I need to respond according to my comments. I would implemented the whole query object system like this:

System classes:

public class Context
{
    // context contains system specific behaviour (connection, session, etc..)
}

public interface IQuery
{
    void SetContext(Context context); 
    void Execute();
}

public abstract class QueryBase : IQuery
{
    private Context _context;

    protected Context Context { get { return _context; } }

    void IQuery.SetContext(Context context)
    {
        _context = context;
    }
    public abstract void Execute();
}

public class QueryExecutor
{
    public void Execute(IQuery query)
    {
        query.SetContext({set system context});
        query.Execute();
    }
}

Concrete query classes:

public interface IActiveUsersQuery : IQuery // can be ommited
{
    int InData1 { get; set; }
    string InData2 { get; set; }

    List<string> OutData1 { get; }
}

public class ActiveUsersQuery : QueryBase, IActiveUsersQuery
{
    public int InData1 { get; set; }
    public string InData2 { get; set; }

    public List<string> OutData1 { get; private set; }

    public override void Execute()
    {
        OutData1 = Context.{do something with InData1 and InData};
    }
}

And you use it like this:

QueryExecutor executor;

public void Example()
{
    var query = new ActiveUsersQuery { InData1 = 1, InData2 = "text" };
    executor.Execute(query);

    var data = query.OutData1; // use output here;
}

It still has same advantages of query-object system. You still get ability to decorate either specific queries or any query (you are missing that in your design). It also reduces objects per query to 2 and you can reduce it to only 1 if you don't need the specific query interface. And there are no nasty generics in sight.

And one specialization of above example:

public interface IQuery<TResult> : IQuery
{
    TResult Result { get; }
}

public class QueryExecutor
{
    // ..

    public TResult Execute<TResult>(IQuery<TResult> query)
    {
        Execute((IQuery)query);
        return query.Result;
    }
}

public class ActiveUsersQuery : QueryBase, IQuery<List<string>>
{
    public int InData1 { get; set; }
    public string InData2 { get; set; }

    public List<string> Result { get; private set; }

    public override void Execute()
    {
        //OutData1 = Context.{do something with InData1 and InData};
    }
}

And then use is reduced to single line :

public void Example()
{
    var outData = executor.Execute(new ActiveUsersQuery { InData1 = 1, InData2 = "text" });
}
Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • 1
    The whole purpose of the pattern is to abstract away the implementation from the specification (and to make it extendable without having to modify existing code). You tie the usage to a specific implementation. Also, by not specifying the result in the interface it's impossible to decorate the implementation before returning it from the factory. – jgauffin Oct 10 '12 at 07:17
  • How do I tie it with specific implementation? Why it cannot be decorated in factory? Do you think it would be possible to decorate in your factory with generics everywhere? – Euphoric Oct 10 '12 at 07:19
  • `new ActiveUsersQuery` = creating the implementation by yourself. Feel free to change the executor and show how you would implement a caching decorator which works for all queries. – jgauffin Oct 10 '12 at 07:20
  • But creating implementation by yourself has nothing to do with separation of interface and implementation. Show me how would you implement caching in your design. You would need to implement Equals for each TParameters. – Euphoric Oct 10 '12 at 07:24
  • @jgauffin And how would you handle invalidation of said cache? IMO caching on queries is not good idea. – Euphoric Oct 10 '12 at 07:27
  • How I implement caching or how I invalidate the cache is not relevant for the question. The main point is that your solution prevent decorators. And by using your context you make all queries dependent of the exact same database implementation (or else you have to start mapping contexts to each specific query or create a god context for all db implementations). Your `SetContext` is also an initializer method (temporal coupling: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx) – jgauffin Oct 10 '12 at 07:39