What is better for a repeating piece of code?

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 code fragments, the code is sharedPart()duplicated. I want to get rid of duplication.

The general part of the code does not need access to any member of the class. Therefore, I can implement it like any of the three:

  • static member function
  • constant function of a non-static member or
  • local function.

Which option is better and why?

+5
source share
7 answers

If your function accesses the state but does not change it, use the const member function.

Your case:

1) , 2) , .

, , .

, :

, . SharedPart - , . First(), Second(), Third(), Fourth(),..., . , SharedPart(); -, First(), Second(), THird(),... SharedPart() .

+5

:

  • , , , " ", " ".
  • , , , , " ". , : , " " namespace beware_of_the_leopard.
  • - .cpp, , , .cpp. , .
+3

.

, , .

, . , - , .

  • ,
  • , .h , .c
+1

-

.

, , -! .

- , , , .

, :

namepsace Astuff{
  class A{...};

  void sharedPart(){...};

  void first(const A& a);
  void second(const A& a);
}

void Astuff::first(const A& a){
   a.first();
   sharedPart();
}
+1

-, const - .

, - , , . - , , . -, , ?

, . , .

: , ; , ; , ... .. , ( ) ArithmeticsForSpecificPurpose.

0

, . ( 23 Effective ++ 3rd Edition).

0

, " , ".

, , , , .

, , , . , , , , , , , , .

, , .

, - mulitple, header/implementaion, .

Whether you put this function in a namespace, in a global scope, or as a static function in a class, it really is to your taste.

In a final note, if you go for a global static function, there is a version of "C ++ like": anonymous namespaces. It has the good property that it can actually maintain state, and also does not allow users to force even to declare any of their functions.

// in your .cpp file
namespace /*anonymous*/
{
   void foo()
   {
     // your code here
   }
};

void MyClass::FooUser1() { foo(); }
void MyClass::FooUser2() { foo(); }
0
source

All Articles