Search code examples
oopdesign-patternsaggregationcomposition

Object Composition - Should a Constituent Know the Composing Object?


I'm building an application that has reports, and each report contains several results. This is definitely a HAS-A composition type relationship between report and result.

My question is this: should a result know to which report it belongs?

Method A (where a result doesn't know which report it belongs to):

Report:
    name
    id
    results[]


Result:
    value
    type
    id

Method B (where a result knows which report it belongs to, but the report doesn't contain the results):

Report:
    name
    id

Result:
    value
    type
    id
    report_id

Solution

  • I think it is impossible to answer this question with the information given, so instead of a straight forward answer, lets look at the things that might influence the decision:

    Do you need the back reference? Obviously, if you don't need it, don't create it. If you do need it though you might still be able to replace it with some kind of Repository lookup like: ReportRepository.findReport(Result)

    What are the costs for the backreference vs. the cost of not having it? If you include a backreference, if the ownership changes (probably won't happen in your case) two references need to be kept in sync. If you don't have the backreference but need to navigate in this direction you have to jump through extra hoops. When persisting bidirectional relations, things like JPA mappings become much more complex. Same thing might apply when you need to serialize Results in some way.

    It might also be worth it to look in to the Aggregate pattern from DDD although it doesn't seem to apply in your case.