Link to home
Start Free TrialLog in
Avatar of MajorBigDeal
MajorBigDealFlag for United States of America

asked on

Is there a way to control class coupling in C#

In part of my design I have two classes, A and B, that are both aware of a common data structure C (also a class).  While most of the contents of A and B are private or protected, there are some public members for various reasons. A and B are supposed to be completely decoupled - I would like to enforce a rule at compile time that says that A will not talk to B directly at all and vice versa. Logic using these two classes (or instances of these 2 classes) would be by a 3rd party generally using an instance of the common data structure C.  

I was wondering about a good way to express this rule in my code (the rule being that A and B are completely decoupled).  Would namespaces be good for this and/or is there another way?
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

No, I believe different namespaces are not enough. It is possible to add reference to one of namespaces to another - and it's possible to refer to classes in this namespace. Of course, circular references are not allowed - namespace two cannot refer to the first one...

Honestly, I can't see any way to do what you want (if I understand requirements properly).
Avatar of MajorBigDeal

ASKER

I should clarify that this code won't get used outside of some internal projects.  It would be similar reasons to why I use private members whenever possible. I could always change them to public if I wanted to but private clarifies my intentions and makes maintenance easier.

So I was thinking that I could fairly easily check that there is no using statement but other than that how would I check that the 2 classes are not interdependent?  Isn't there some mechanism to address this? I was wondering what other programmers do in this situation or am I just dithering on stuff that is not important?
ASKER CERTIFIED SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Your mediator suggestion is very interesting to me, although I don't think I fully understand it.  Let me try to do a better job of explaining what I am doing currently.  I am passing an instance of C to public methods of both A & B as a parameter.  Class A is also capable of generating an instance of C which might be subsequently passed into B (possibly after modification).   What I think you are suggesting is that class A & B could both be private inside class C - that would not work for me because class A and B are both used in other places.  
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial