Search code examples
c++refactoringcommon-code

C++ refactor common code with one different statement


I have two methods f(vector<int>& x, ....) and g(DBConn& x, ....) where the (....) parameters are all identical.

The code inside the two methods are completely identical except for one statement where we do different actions based on the type of x:

in f(): we do x.push_back(i)
in g(): we do x.DeleteRow(i)

What is the simplest way to extract the common code into one method and yet have the two different statements?

I am thinking of having a templated functor that overloads operator () (int a) but that seems overkill.


Solution

  • You could write a simple adapter with two implementations, each calling the desired method of a different class.

    class MyInterface {
    public:
      virtual doIt(int i) = 0;
    }
    
    class VectorImp : public MyInterface {
    public:
      vector<int>& v;
      VectorImp(vector<int>& theVector) : v(theVector) {}
      doIt(int i) { x.push_back(i); }
    }
    
    class DbImp : public MyInterface {
    public:
      DBConn& c;
      VectorImp(DBConn& conn) : c(conn) {}
      doIt(int i) { c.DeleteRow(i); }
    }