I have 2 entities with a parent-child relation (like a base product and product variants), basically the two entities have the same properties and at runtime (when instantiating the object) if the the property X have a value in the parent then the same property X should have the same value for the child entity instance.

I try to emulate this behavior by having a property 'parent' in the child entity. Not a mere pointer to the parent but the complete parent object instance, so I can decide from the child perspective if a given property should take the parent (accessible through the parent property) value or have its value "override" ...

I post here to know if there is a better way (pattern ?) to achieve this ? because I feel like instantiating the full parent object inside the child is not the best way to do it but I can't think of a better/simpler alternative ....

in pseudo code :

parent = new ProductBase(name:="abc123")
child = new ProductVariant(parent:=parent)
child->getName() // returns the value from the parent ("abc123") because it has noit been overwritten inside child instance
child->getName() // returns the overridded value i.e. "def3456"

Thanks for your help/suggestions !

  • 1
    It sounds like you have a typical inheritance relation, not a parent-child relation.
    – Rik D
    Jun 13 at 9:17
  • but it's an inheritance of values (at instantiation) not just what kind of property is in the object Jun 13 at 9:20
  • It's hard to say when you think you have a composition of entities when you (really) might have an inheritance. It's not clear to me. Could you illustrate with snippets? (It can be in any language or pseudo-code). I have a hard time understanding what you have implemented so far.
    – Laiv
    Jun 13 at 9:58
  • 1
    So, if you ever do child->setName(null), the response of child->getName() is abc123? And Is it this way for every common attribute between "parent" and "child"? If yes, then you have a very common "wrapper" or "decorator".
    – Laiv
    Jun 13 at 10:25
  • 1
    Patterns don't belong to frameworks. Frameworks implement patterns and offer "ports" for you to implement your "adapters" and integrate your code with the framework. It's all up to you if you introduce FWK-specific dependencies in your domain or not. The best way to avoid this is by coding your domain as a standalone module with no other dependency than the SDK and utility libs. As for the "best pattern". Stop thinking in terms of"best/worse". Start thinking in terms of adequacy or simplicity or readability. Solve the problem first. Improve (if necessary) later. –
    – Laiv
    Jun 13 at 11:16


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.