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?