0

I'm writing an application and following the Data Mapper pattern.

I've ended up in a situation where two data mappers depend on each other. Specifically, I have a Parent type that has Child objects. When a parent is modified, it needs to get a list of its children and process them a bit. When a child is modified, it has to check the state of its parent. This leads to classes structured like so:

class ParentMapper {
  ParentMapper(ChildMapper childMapper) { ... }
  void save(Parent p) {
    Child[] children = childMapper.list(p.getId());
  }
}

class ChildMapper {
  ChildMapper(ParentMapper parentMapper) { ... }
  void save(Child c) {
    Parent p = parentMapper.get(c.getParentId());
  }
}

I can't create either without the other being created.

What is a good way to handle this? While I'm not required to use the Data Mapper pattern, I have found it to be a nice clean abstraction.

This is Java with Guice, for reference.

Richard Levasseur
  • 14,562
  • 6
  • 50
  • 63
  • 1
    Instead of giving the both constructor the parameter, give one of the classes an method that sets its child/parent mapper. Otherwise there is no way around this indeed. – n247s Apr 19 '16 at 04:57
  • Guice will create a proxy object to satisfy one of the dependencies during initialization, then swap it out. It handles dependency cycles automatically. Are you seeing a specific error? – Cardano Apr 27 '16 at 18:42

1 Answers1

0

Maybe, for your purposes you should provide ChildMapper as a dependency for your ParentDomainObject, not for ParrentMapper, and ParrentMapper as a dependency for your ChildDomainObject, not for ChildMapper. And then, you may process children a bit in ParentDomainObject before save() method call. Similar for checking the state of Parent, you may do it before call save(). There are some thoughts that it`s not a good practice to use one data mapper inside another data mapper, and to make them depend on each other.

(Using data mapper inside another data mapper in Java?)

I don`t think that this is responsibility of ParentMapper to modify ChildDomainObject, and vice versa.

Community
  • 1
  • 1