Im not sure if this is a stupid question, so shoot me if it is!
I am having this “dilemna” which I encounter very often. I have say two overloaded functions in C++
say we have this two overloads of F (just a pseudocode below)
void F(A a, .../*some other parameters*/)
{
//some code part
//loop Starts here
G1(a,.../* some other parameter*/)
//loop ends here
//some code part
}
void F(B b, .../*some other parameters*/)
{
//some code part
//loop Starts here
G2(b,.../* some other parameter*/)
//loop ends here
//some code part
}
where A and B are different types and G1 and G2 are different functions doing different things. The code part of the overloads except for G1 and G2 lines are the same and they are sometimes very long and extensive. Now the question is.. how can I write my code more efficiently. Naturally I want NOT to repeat the code (even if it’s easy to do that, because its just a copy paste routine). A friend suggested macro… but that would look dirty. Is this simple, because if it is Im quite stupid to know right now. Would appreciate any suggestions/help.
Edit: Im sorry for those wanting a code example. The question was really meant to be abstract as I encounter different “similar” situation in which I ask myself how I am able to make the code shorter/cleaner. In most cases codes are long otherwise I wouldn’t bother asking this in the first place. As KilianDS pointed out, it’s also good to make sure that the function itself isn’t very long. But sometimes this is just unavoidable. Many cases where I encounter this, the loop is even nested (i.e. several loops within each other) and the beginning of F we have the start of a loop and the end of F we end that loop.
Jose
The most obvious solution is to put the common code parts into separate
functions, and call them:
if there is a lot of data shared between the prefix and the postfix, you
could create a class to hold it, and make the functions members.
Alternatively, you could forward to a template, possibly using traits:
This could easily result in the common parts of the code being
duplicated, however. (Whether this is a problem or not depends. In
most cases, I suspect that the code bloat would be minimal.)
EDIT:
Since you say that the common code includes the loop logic: you can use
the template method pattern, something like:
You then define a separate derived class in each function:
The fact that you need the forwarding constructor makes it a bit wordy,
but it does keep all of the common code common.