Wednesday, 28 September 2005

Seperate logic from persistence

One thing that I have found writing software and testing it as I go is to structure an application in a way to make it easy to test. I find it much easier to do this when you separate any logic from where you persist data by saving it to a db or file or whatever. I always work best with examples, so let's use one: I need a class that will use complex (or not so complex) logic to create widgets and then save those to a db.

Here's one way to do it:
doEverythingMethod() {
 for (loopCondition) {
  // complex logic to decide what kind of widget to make
  saveWidget();
 }
}


Now, that's all well and good. However to test the logic of the method then you will end up making tons of widgets to the db. You might want to clean it up out of the db, but in the end you are making the test slow by saving things to the db when all you want to do is test the logic.

Here's another solution:
doEverythingMethod() {
 collectionOfWidgets = complexLogicMethod();
 for (eachWidget in collectionOfWidgets) {
  saveWidget();
 }
}
Collection complexLogicMethod() {
 // complex logic to decide what kind of widget to make
 return collectionOfWidgets;
}

The second way will allow you to test the complex logic in an isolated way. The doEverythingMethod() in the second example then needs less aggressive testing since it's simpler.

Short answer: slightly different structure of the application will make testing easier and faster.

No comments:

Post a Comment