views:

109

answers:

2

Hi Guys, a bit of help.

I have an application which executes multiple queries (query1, query2, query3) against a DB, retrieves data and then publishes that data.

The way I went about designing it was:

a. Have a DB class which encapsulated the connection, query execution, transforming resultset to POJOs.

b. A publisher class which knows how to publish the pojo.

c. A controller which, at start, executes a and then feeds the output to b.

public void start(){
    List<DataPojo> pojoList = db.executeAndRetrieveResult();
    for (DataPojo p : pojoList){
       publisher.publish(p);
    }
}

d. A manager which contains a list of controller. When invoked, iterates and asks the controller to start.

public void start(){
   for (Controller c : controllerList){
       c.start();
   }
}

The life of the app was simple and thus good.

But now I need to make a change which entails, taking data from query1, combining with the data from query2 and then publishing it.

Previously, the Controllers were homogeneous. The difference between them was encapsulated in the query that they executed (using the Db class).

However, now I need to know which controller is executing which query so I know where to get the output of query1 and query2.

Is a design pattern that I can use to make Controller1 and Controller2 interact while still keeping them relatively loosely coupled?

Cheers

+2  A: 

The common thing people do here is to separate the application into layers. The "bottom" layer (or the layer closest to the db) just interacts with the database and deals with simple db entities. If this isn't sufficient there's usually a "business layer" where you'd put logic for combining db entities, wrapping objects built from combinations of atomic db entities, etc.etc.

The front end, whatever it is, interacts with the business layer. The main point is to avoid mixing the business logic (how the db entities will combine) with the db logic (getting and setting values for individual db entities).

As a pattern, you'll find discussions of this under headings like "3-tier" or "N-tier" design.

Steve B.
+1  A: 

I'd create a wrapper interface for your queries, something like QueryExecutor, which then has two implementations. A simpleQueryExecutory which just exec one query like you have now, and a MultiQueryExecutory or LinkedQueryExeutor (or some such, you get the idea) that takes in the two queries that are related.

Have your MultiQueryExecutor class execute the two queries and then do your post query processing logic before returning the now combined published data.

This also sets you up for all sorts of potential flexible query execution later, like a StopOnFirstResultsMultiQueryExecutor where you can feed it a List of queries, but it'll stop and publish the results of the first one that finds > 0 results. That's just an example off the top of my head, but hopefully it gets the point across.

Chris Kessel