Thursday, August 02, 2007 5:56 AM
So I am getting ready to write up some code that needs to do some daily processing every day except for the first of the month where it needs to do some additional work. It first I had a method that looked something like this:
public void RoutineMaintenance()
{
if(isFirstOfTheMonth)
{
ImportDataFromThirdPartySources();
}
GenerateInvoices();
CheckOverduePayments();
UpdateTransactionsFromPaymentSource();
if(isFirstOfTheMonth)
{
ExportDataToThirdPartySources();
}
}
So what I don't like about this is the double 'if's. I know that it can be a minor issue but I see it as cluttering up the code. So after thinking about it I thought, I could use the strategy pattern + the decorator pattern to better implement this code.
public interface DailyProcess { void Perform(); }public class StandardProcess : DailyProcess
{
public void Perform()
{
GenerateInvoices();
CheckOverduePayments();
UpdateTransactionsFromPaymentSource();
}
}
public class FirstBusinessDayOfTheMonth : DailyProcess
{
DailyProcess innerProcess;
public FirstBusinessDayOfTheMonth(DailyProcess innerProcess)
{
this.innerProcess = innerProcess;
}
public void Perform()
{
ImportDataFromThirdPartySources();
innerProcess.Perform();
ExportDataToThirdPartySources();
}
}
public class RoutineMaintenance
{
DailyProcess process;
public RoutineMaintenance(DailyProcess process)
{
this.process = process;
}
public void PerformDailyProcess()
{
process.Perform();
}
}
This "improvement" uses a lot more code and you can cleary see that it adds complexity, but now I can easily configure RoutineMaintenance do handle a variety of tasks by just loading up the daily process. My new code being called might look like
Dictionary<bool, DailyProcess> processes = new Dictionary<bool, DailyProcess>();
processes.Add(true, new new FirstBusinessDayOfTheMonth(new DailyProcess()));
processes.Add(false, new DailyProcess());
//later in the app
RoutineMaintenance maint = new RoutineMaintenance(processes[isFirstBusinessDayOfTheMonth]);
maint.PerformDailyProcess();
This kind of stuff is a lot easier with frameworks like Castle, and Spring.