Skip to content

Instantly share code, notes, and snippets.

@tjaskula
Last active August 29, 2015 14:05
Show Gist options
  • Save tjaskula/1101258816984cc64e64 to your computer and use it in GitHub Desktop.
Save tjaskula/1101258816984cc64e64 to your computer and use it in GitHub Desktop.
I tend to avoid breaking CQS principe in OOP. But there are sometimes cases that it would be possible to do it for a simpler code.
//1. breaking CQS
var sor = new SimpleOrderRouting();
var orderConfirmation = sor.Route(new OrderRequest(..));
bool isOrderExecuted = orderConfirmation.ExecutionCompleted;
//2. adhering to CQS not blocking
var sor = new SimpleOrderRouting();
bool isOrderExecuted = false;
sor.ExecutionCompleted += response => {
isOrderExecuted = response.ExecutionCompleted;
}
sor.Route(new OrderRequest(..));
//3. adhering to CQS way blocking
var sor = new SimpleOrderRouting();
var orderRequest = sor.PrepareRequest(...);
sor.Route(orderRequest);
bool isOrderExecuted = orderRequest.ExecutionCompleted;
//4. adhering to CQS with observer pattern
public interface IOrderExecutionHandler
{
void Notify(ExecutionResponse response);
}
//...
var sor = new SimpleOrderRouting();
var orderRequest = new OrderRequest(..);
IOrderExecutionHandler oeHandler = new OrderExecutionHandler();
sor.Subscribe(oeHandler);
sor.Route(orderRequest); // invokes Notify method on observers
// other way ?
@ploeh
Copy link

ploeh commented Aug 20, 2014

What's wrong with number 2?

To be fair, it's difficult to see if you're violating CQS in any of these examples, because we can't see the signature of the containing method.

@tjaskula
Copy link
Author

For simplicity. The containing method call "sor.Route" is running an algorithm on OrderRequest object, finds to which financial market the order should be routed, creates a Market object which is a proxy to the financial market and calls a method on it "market.Send(marketOrder)". Then the market proxy calls back when order is executed so "sor" can notify the client with this bool isOrderExecuted = orderConfirmation.ExecutionCompleted;

I like the most the number 2 because I'm being called back when something of interest happens to me. But it seems that without using events it's hard to adhere to CQS and have readable code.

Is it more clrear or more context should be provided ? How would you write a CQS compliant code differently that in a two last steps ?

@ploeh
Copy link

ploeh commented Aug 20, 2014

Ah, use Rx instead of .NET events :)

@ploeh
Copy link

ploeh commented Aug 20, 2014

Or just use the Observer pattern.

@yreynhout
Copy link

or return a promise/future/task (could be custom code)?

@tjaskula
Copy link
Author

@ploeh : With the observer pattern that I've added it seems to clunky. Or maybe you would do it in another way.

@yreynhout could you elaborate ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment