Reputation: 11753
I give the following examples to illustrate my question:
class B;
class A
{
public:
class B *pB;
};
class B
{
public:
void perform(A &obj)
{
}
};
In the above two classes. class A has a pointer to class B. class B has a function that will work on class A object. Though it can compile, I was wondering whether this is not a good practice for designing two classes as they are intertwined. If this is bad design, do you have some ideas to avoid it? Thanks.
Upvotes: 2
Views: 123
Reputation: 19232
Having two concrete classes rely directly on one another can get you into trouble.
It is often better to "program to an interface". There is a long discussion here under the title "Program to an interface, not an implementation", which draws out why decoupling matters
In your example, void perform(A &obj)
could instead take an abstract base class that A
derives from. It might be worth having an interface that A
uses in it's member variable too, but there' no suggested usage in your example to go on.
Why is this "better"? For starters, it will make you think about encapulsation - and what specifically the interface should be exposing.
It will also allow you to use different conrete instantions of the class, say for testing purposes.
If you use an interface, you can change the conrete classes separately... there are many advantages.
Upvotes: 3