Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring a class

I have two almost identical classes, in fact every member function is identical, every member is identical, every member function does exactly the same thing. The only difference between those classes is the way I can define variable of their type:

AllocFactorScientific<102,-2> scientific;
AllocFactorLinear<1.2> linear;  

Here are headers for them:

template<double&& Factor>
struct AllocFactorLinear;

template<short Mantissa, short Exponent, short Base = 10>
struct AllocFactorScientific

My question is how can I refactor those functions out of those classes that would allow me to have just one set of functions and not two sets of identical functions.

like image 524
There is nothing we can do Avatar asked Nov 25 '10 21:11

There is nothing we can do


1 Answers

Extract all the common behavior in a third class (I'm omitting the template arguments in my answer for the sake of clarity) :

class CommonImpl
{
public:
  void doSomething() {/* ... */ }
};

I then see two choices (which are, from my point of view at least, pretty much equivalent) :

  • Make AllocFactorLinear and AllocFactorScientific inherit privately from this class, and bring the member functions you wish to expose in scope with a using directives :

    class AllocFactorLinear : CommonImpl
    {
    public:
      using CommonImpl::doSomething;
    };
    
  • Aggregate the implementation class in AllocFactorLinear and AllocFactorScientific and forward all the calls to the private implementation :

    class AllocFactorLinear
    {
    public:
      void doSomething() { impl_.doSomething(); }
    private:
      CommonImpl impl_;
    };
    

I would personally go for the first solution.

like image 122
icecrime Avatar answered Sep 23 '22 15:09

icecrime