A Curious Mind
#tastic

Command Query Separation

Sunday, June 03, 2007 12:08 PM

The fundamental idea is that we should divide an object's methods into two sharply separated categories:

  • Queries: Return a result and do not change the observable state of the system (are free of side effects).
  • Commands: Change the state of a system but do not return a value.

So I have been thinking a lot about Command Query Separation (CQS) lately as I not long ago ran into a Heisen Bug that thankfully didn't take a lot of time to spot or fix but mostly just made me aware of the problem.

However, as I ruminate on the concept and try to implement it into code I end up writing code like:

public class Loan
{
  public double CalculateInternalRateOfReturn(IirCalculator calculator)
  {
    return calculator.Calculate(this.Principal, this.Payments);
  }
  
  public void UpdateInternalRateOfReturn(IirCalculator calculator)
  {
    this.InternalRateOfReturn = this.CalculateInternalRateOfReturn(calculator);
  }
  
  public void AddPayment(Payment payment)
  {
    this.Payments.Add(payment);
    this.UpdateInternalRateOfReturn()
  }
}

It seems silly to have all of these little one line methods in my classes, but now that I have typed it out, I actually like the way it looks. The methods are very simple to understand, and should also be quite easy to test. I still worry about the quantity of methods that may be created in my classes, which could make using the class difficult (because I prefer to make all of my methods public rather than private). Hopefully after the class is fully fleshed out I will find that other objects are hidden in the class that I can then extract from my current class.

Anyways, I would love to hear any feedback the group may have on how the approach these situations as well.

-d


Feedback

No comments posted yet.


Post a comment





 

Please add 2 and 2 and type the answer here: