How to prevent duplicate code in different for loops?
50
50
Jan 04, 2011
I've got a class, let's say a "mutual fund portfolio". It's got 3 methods that calculate 3 different numbers each using a for-loop. Most of the steps in the 3 different methods are exactly the same, except for 1 or 2 steps.
Is there a smarter way to prevent duplicate code than just writing 1 base method and using a case statement for the 3 different numbers to be calculated? I looked at the "Template Method Design Pattern" but that doesn't seem to be applicable.
You can find some simplified code underneath. The difference is in the "DoCalculationsWithMemberVariables_Step3" step of the "Test_MeasureX_Historically" methods. Those differ.
Public Class MutualFundsPortfolio
Public Sub Test_Measure1_Historically()
Dim j As Integer
Dim lNrOfPeriods As Integer
lNrOfPeriods = 20
For j = 1 To lNrOfPeriods
DoCalculationsWithMemberVariables_Step1
DoCalculationsWithMemberVariables_Step2
DoCalculationsWithMemberVariables_Step3a
DoCalculationsWithMemberVariables_Step4
Next j
End Sub
Public Sub Test_Measure2_Historically()
Dim j As Integer
Dim lNrOfPeriods As Integer
lNrOfPeriods = 20
For j = 1 To lNrOfPeriods
DoCalculationsWithMemberVariables_Step1
DoCalculationsWithMemberVariables_Step2
DoCalculationsWithMemberVariables_Step3b
DoCalculationsWithMemberVariables_Step4
Next j
End Sub
Public Sub Test_Measure3_Historically()
Dim j As Integer
Dim lNrOfPeriods As Integer
lNrOfPeriods = 20
For j = 1 To lNrOfPeriods
DoCalculationsWithMemberVariables_Step1
DoCalculationsWithMemberVariables_Step2
DoCalculationsWithMemberVariables_Step3c
DoCalculationsWithMemberVariables_Step4
Next j
End Sub
End Class
548
99.9
Jan 04, 2011
Hi, I thought I'd take a crack at this. I'm still learning like you, and this is what I came up with. It's a small VS 2008 Console project that uses the Strategy Pattern and other cool stuff. It's probably not exactly what you need but it does what you need without duplicating code.
This was kind of fun. Three years ago I could never do this.
Here's some code from the attached file example.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter one of the following values:");
Console.WriteLine(" Test1, Test2, or Test3");
// Read the input value
// Valid values are: Test1, Test2, Test3
string testType = Console.ReadLine();
// Convert the string type to the Enum type.
HistoricalItems key = (HistoricalItems)Enum.Parse(typeof(HistoricalItems), testType.ToLower());
// Instantiate a new Portfolio context.
MutualFundsPorfolio portfolio = new MutualFundsPorfolio();
// Process the selected item type.
portfolio.Process(key);
Console.ReadLine();
}
}
You can download the file here: http://www.kingwilder.com/downloads/strategyexample.zip - 51KB - VS 2008 project
This zip file contains both VB.Net and C# examples.
I hope it helps.
King Wilder