How to prevent duplicate code in different for loops?
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.
G. Van Dam, 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.
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, Jan 04, 2011