Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is best for a repeating piece of code?

Tags:

c++

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:

  • a static member function,
  • a const non-static member function or
  • a local function.

Which variant is better and why?

like image 768
sharptooth Avatar asked Jun 25 '09 11:06

sharptooth


People also ask

What is used to repeat a code?

The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.

What do you call a section of code that repeats?

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.

What is it called in coding when we repeat code multiple times?

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.

Why should we use repeat loops in our code?

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.


1 Answers

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.

like image 144
Brian R. Bondy Avatar answered Sep 23 '22 01:09

Brian R. Bondy