Imagine these relationships:
- 1 A has many B's
- 1 B has many C's...
In reverse:
- C has 1 B
- B has 1A
- By transitivity, C has 1 A
To model this relationship in DB, we have:
TableA
a_id
TableB
b_id
a_id (fk to TableA)
TableC
c_id
b_id (fk to TableB)
To model this relationship in OO, we have:
objA
objB
objC
And... - objB has reference to objA - objC has reference to objB
If objC has a method that needs to call a method of objA, what will you do?
Option 1.
b.getA().runMethodX()
Many ppl I know would do this, but I've also learned that this is not good because getA() is not a behavior of B in a pure OO sense. Doing so is just like doing procedural programming. Agree/Disagree?
Option 2.
Let objC has direct reference to objA and objB through constructor injection / setter
Is this a good idea? but then objB that objC has reference to also has reference to objA. Is this okay? Or as long as it is not a case of cyclic object references, it is acceptable?
Option 3.
Move the method in question to objA, and pass objC in by parameter.
I'm not sure if this considers as an option. I think it'll not work in every case. Have the method in objC reduce to bare minimum that only works on its states, and let objA do whatever objA needs to do before or after.
Option 4. (Delegation)
add runMethodXinA() to B, it calls
a.runMethodX()
C calls
b.runMethodXinA()
I tried this method before, but B will very likely end up having as many methods as A, and doesn't having 1 method in both B and A violates DRY?
What are your though? Any other options? Comments? Suggestions?
Thank you!