Wednesday, June 30, 2010

Using Model-View-Controller differently - to isolate volatile parts of your application

Even if your application does not have a GUI, you can benefit from MVC.
I was trying to write automated tests using JUnit/Cactus and it quickly got unmanageable.
Each test case involved creating several business objects, filling each with lots of data, and then invoking on business services. Since there were different combinations of the data, for each test case, one had to create a new class. Ridiculous!
The solution was:
View (interacting with the outside)
This was not a GUI, but simply a JUnit class.
TestCases contains the test methods, and inherits from JUnit’s TestCase. It has a reference to the concrete data set and instantiates the specific data set. TestDataSet0, TestDataSet1…
It invokes on TestDataSet0 to retrieve the BusinessObjects object to perform its testcases.

Model (Volatile part)
Interface TestDataSet has getter methods
BusinessObjects getBOCombination1()
BusinessObjects getBOCombination2()…
Concrete class TestDataSet0,1,2… implements this interface.
It has a reference to class BusinessObjects.
The data can be filled from the database, or simply hardcoded.

Controller
Class BusinessObjects contains methods to populate each Business Object.
populateBO1(), populateBO2()

So each time there is a different combination of data, create a class TestDataSet_N - yes, it is another class but all it is concerned with is the hardcoding of data, or retrieving of that data combination from the database.

The advantage of this design is, it allows reuse of methods, isolates the hard-coded data (that keeps changing from case to case) and enables more rapid progress.

No comments: