I have a class with two member functions that share a piece of code:
void A::First()
{
firstFunctionEpilogue();
sharedPart();
}
void A::Second()
{
secondFunctionEpilogue();
sharedPart();
}
Currently firstFunctionEpilogue()
, secondFunctionEpilogue()
and sharedPart()
are not function calls but just pieces of code, sharedPart()
code being duplicated. I want to get rid of the duplication.
The shared piece of code doesn't need access to any members of the class. So I can implement it as any of the three:
Which variant is better and why?
The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.
A loop executes the same section of program code over and over again, as long as a loop condition of some sort is met with each iteration. This section of code can be a single statement or a block of statements (a compound statement). Loops and Using Loops. Repetition allows the programmer to efficiently use variables.
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number.
Programming Application: When programmers write code, loops allow them to shorten what could be hundreds of lines of code to just a few. This allows them to write the code once and repeat it as many times as needed, making it more likely for the program to run as expected.
If your function accesses state but does not change it then use a const member function.
Your case:
If it your function 1) doesn't need access to any member of the code, and 2) is related to that class, then make it a static function of your class.
That way it is clear that it is not modifying state, nor based on the state of the object.
An extra case you didn't mention:
There is another thing you can do too. And that is to make your SharedPart take in a member function pointer and to call it and then process it's main body. If you have a lot of First(), Second(), Third(), Fourth(), ... such functions then this can lead to less code duplication. That way you don't need to keep calling SharedPart(); at the end of each member function, and you can re-use First(), Second(), THird(), ... without calling the SharedPart() of the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With