This often happens in my projects. Sometime I have this part of code that is very similar to this other part, yet a few lines makes it complicated to keep the code clean and without duplication. Here is an example of a recent project.
I am working on a program which can do 2 things : A will generate an image projected in some way, and B will generate several images in some other projection.
Choice A:
void generateImage(width, height) { vector<Pixel> pixels; for(x = 0; x < width, x++) { for(y = 0; y < height; y++) { Position pos = projectPixel(x, y); Pixel p = someCrazyFunc(pos); pixels.add(p); } } }
Choice B:
void generateImage(width, height, numImages) { vector< Pixel > pixels; for(image = 0; image < images; image++) { for(x = 0; x < width, x++) { for(y = 0; y < height; y++) { Position pos = projectPixel2(x, y, image); Pixel p = someCrazyFunc(pos); pixels.add(p); } } } }
As you can see, that’s pretty much the same. The only difference with A is that we dont compute pos the same way, and that we need to generate several images.
In practice, this is a bit different since there is more code. Basically, there is more loops because we need to compute all the pos of a loop before calling someCrazyFunc, and because we compute images by slices (first 1000th row, then 1000 more, etc). I’m mentioning this just to say that this isn’t just 4 lines which get duplicated, but loops and function calls.
I fixed it this way:
void generateImage(width, height, numImages, projectPixelFunction) { vector< Pixel > pixels; for(image = 0; image < images; image++) { for(x = 0; x < width, x++) { for(y = 0; y < height; y++) { Position pos = projectPixelFunction(x, y, image); Pixel p = someCrazyFunc(pos); pixels.add(p); } } } }
So basically for A numImages will be equal to 1, and the old projectPixel function will take a dummy parameter.
I don’t think this is an acceptable solution to the problem. I honestly even prefer to have 2 mostly identical functions. But as the complexity grow, I’ll either have a lot of duplicated code, or a lot of code with weird solutions.
How do I get over this? What am I not considering?