Home > Back-end >  Refactoring : delegate friendship in sub-functions
Refactoring : delegate friendship in sub-functions

Time:04-25

I refactor a code where a class has a friend function doing a lot of stuff.

class Foo
{
  friend void do_something(Foo& foo);
};

void do_something(Foo& foo)
{
  // More than 2000 lines of ugly code
}

I would like to split the content of do_something in several small functions. Something looking like this :

void do_something(Foo& foo)
{
  if(case_1) do_1(foo);
  else if(case_2) do_2(foo);
  else if(case_3) do_3(foo);
  //...
}

Is there a design where I can transfert the friendship to the sub-fuctions do_x(Foo&) without having to declare them in the class, or something similar in order to split the code ?

Note : C 11 only

Note : I don't want to write the sub-functions as maccros

CodePudding user response:

Instead of having do_something as function calling other sub-functions, I would suggest you to create an analogous class DoSomehting.

Then you could declare this class as a friend with friend class DoSomehting;. So these sub-functions could be its private methods. The method to call -- could be a public method named e.g. like void DoSomehting::process(Foo& foo):

class Foo
{
  friend class DoSomething;
};

class DoSomething
{
public:
    void process(Foo& foo)
    { 
        if(case_1) do_1(foo);
        else if(case_2) do_2(foo);
        else if(case_3) do_3(foo);
        //...
    }  

private:
    void do_1(Foo& foo);
    void do_2(Foo& foo);
    void do_3(Foo& foo);
};
  • Related