Objects that mutually need each other

I am in a situation where two classes (call A and B ) are connected to each other (their methods rely on the data of the other), but the IS-A relationship is not suitable. I could use composition, so both objects have fields that store another object. But that seems ugly to me. What I'm doing now - to create another class of the C , containing objects from the A and B of the composition, and when I want to call a method on a class A , I pass the object B . My problems with this approach:

  • I need to pass one object to another so that it starts to resemble a simple argument of a function argument instead of the OOP approach, where the object encapsulates its data.
  • If I need to change something, I may need to change the code of both classes A and B , which is not a good time to reuse the code

What do you recommend?

Example

class Mesh:
  method: plot(this, Solver)
          {
             plot data from class Solver // need to pass a Solver object, so the class is not self-contained
          }
  method: intersect(this, Domain)
          {
             do sth // depends on Domain, so we need to pass it
          }

class Domain:
  method: plot(this)
          {
             plot data from own data // no problem
          }
  method: selectVertex(this, Mesh)
          {
             do sth // depends on Mesh, so we need to pass it
          }

Thanks, Zoltan

+4
source share
1 answer

"All problems in computer science can be solved by a different level of indirection, except for the problem of too many layers of indirection" - David Wheeler.

You tried to add another layer of indirection, but that did not solve your problem. So, there is a thing that is fundamentally wrong.

Here is my point:

2 , , , 2 , , , , .

? - , .

0

All Articles