0
class foo
{
    bar b;

    someFunction()
    {
        b.alphaObj->someFunctionOfAlpha();
    }
};


class bar
{
    friend class foo;
    // many more friends

private:
    alpha *alphaObj;
};

How do I remove the friend dependency without exposing the private members with getters and setters. I understand friend classes could help in enhancing encapsulation but there are a lot of friend classes defined in my class exposing the private members to all. Hence I am thinking of a better approach and any help is appreciated.

3
  • 1
    Requiring a lot of friends indicates a set of poorly encapsulated classes - Why do so many classes require access to class bar? Commented Dec 10, 2019 at 9:41
  • We are dealing with legacy code here and that's how it is. We are thinking of refactoring now with a better design Commented Dec 10, 2019 at 9:44
  • 2
    The example here feels a bit too generic to be useful. Generally someFunctionOfAlpha wants to be moved to some other class where it can be made public. It could potentially be a wrapper that say bar creates, or become a member of bar itself. Another option is to pass a callback function and call that, instead of calling whatever it is directly. Commented Dec 10, 2019 at 9:44

1 Answer 1

1

Independent of your friend issue, being required to write this

b.alphaObj->someFunctionOfAlpha();

is not the best design. You should rather call (*):

b.someFunctionOfAlpha();

Now it is also obvious how to remove the friends:

class bar
{
public:
    void someFunctionOfAlpha() { alphaObj->someFunctionOfAlpha(); }

private:
    alpha *alphaObj;
};

(*) This guideline has a name, I just cannot find it at the moment. In general, calling a method should be like: "Do that!". Calling a method should not be like "Show me your internals so I can do what I want".

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. This answer shows a valid point but does not answer the question. Hence not marking as correct
@abhilashanand why does it not answer the question? I show you how you can resolve the need for friend
Yes. But this exposes the inner features of alpha class indirectly by making it public. I have mentioned it as a constraint to not expose the inner functionalities by means of getters and setters
We had a discussion and this was pretty good and hence marked as correct. Another suggestion was the make the member public and make it a const such that it cannot be modified. If there are a lot of variables then your suggestion could result in a lot of code. Thanks for your effort
I think you are referring to "Law of Demeter" above :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.