Note that there are some explanatory texts on larger screens.

plurals
  1. PO2x one-to-many relationships in OO
    text
    copied!<p>Imagine these relationships: </p> <ul> <li>1 A has many B's</li> <li>1 B has many C's...</li> </ul> <p>In reverse: </p> <ul> <li>C has 1 B</li> <li>B has 1A</li> <li>By transitivity, C has 1 A</li> </ul> <p>To model this relationship in DB, we have:</p> <pre><code>TableA a_id TableB b_id a_id (fk to TableA) TableC c_id b_id (fk to TableB) </code></pre> <p>To model this relationship in OO, we have:</p> <pre><code>objA objB objC </code></pre> <p>And... - objB has reference to objA - objC has reference to objB</p> <p>If objC has a method that needs to call a method of objA, what will you do?</p> <p><strong>Option 1.</strong></p> <pre><code>b.getA().runMethodX() </code></pre> <p>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?</p> <p><strong>Option 2.</strong></p> <p><em>Let objC has direct reference to objA and objB through constructor injection / setter</em></p> <p>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?</p> <p><strong>Option 3.</strong></p> <p><em>Move the method in question to objA, and pass objC in by parameter.</em></p> <p>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.</p> <p><strong>Option 4.</strong> (Delegation)</p> <p>add runMethodXinA() to B, it calls</p> <pre><code>a.runMethodX() </code></pre> <p>C calls</p> <pre><code>b.runMethodXinA() </code></pre> <p>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?</p> <p>What are your though? Any other options? Comments? Suggestions?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload