0

I have been reading things about DDD, aggregates and entities and a doubt has come up. Let's say I have the following entity:

    class AnEntity:
          name: str
          
          # command / mutator method
          def change_name(self, new_name: str):
               self.name = new_name

          # query method
          def read_name(self) -> str:
               return self.name

And that I have the following aggregate containing that entity:

class AnAggregate:
        root_id: Id
        an_entity: AnEntity

        def change_name(self, name: str):
            if len(name) < 10:
                raise Exception('Name must be longer')
            self.name = name

Now, supposedly, the theory says that aggregates should:

  • Contain command / query methods.
  • Only query methods should be available on child entities

So in my example, AnAggregate has a child entity called an_entity. So if you do:

an_aggregate = AnAggregate(rood_id=Id('29839afef'), AnEntity(name='name longer than 10 characters'))

# I can modify the child entity, skipping the consistency boundary of the aggregate
an_aggregate.an_entity.change_name('invalid')

So my question is, how do I avoid this case using code? Is there a way to protect the entity?

Antonio Gamiz Delgado
  • 1,871
  • 1
  • 12
  • 33
  • I have no idea where "Only query methods should be available on child entities" comes from -- I've never seen anybody advocate for that constraint on a design. – VoiceOfUnreason Oct 19 '22 at 15:13
  • https://av.tib.eu/media/44889 -> Minute 30:18 – Antonio Gamiz Delgado Oct 19 '22 at 15:17
  • 1
    @AntonioGamizDelgado I also don't think there is such a rule (I couldn't hear it in minute 30:18 btw). I think it's just a convenience when coding aggregates. In fact, in minute 26:30 he says "you can put mutating commands on the child entities but then it gets more awkward to maintain consistency amongs the other entities within that aggregate". As this is more of a code styling, it'll depend on the team that's working on the project. You can simply write it in the coding style guide or enforce it with a custom rule in your code linter (a bit overkill imo). – Francesc Castells Oct 19 '22 at 22:45
  • Oh you are totally right. I was looking at the slides only because I heard the talk some time ago. Thanks! – Antonio Gamiz Delgado Oct 20 '22 at 07:11

0 Answers0