Skip to content
Advertisement

What nested class type is best suitable for Domain Events?

I am following Domain Driven Design and Clean/ Hexagonal architecture in my Java microservice. I have domain events declared in my aggregate root class as non-static nested classes. My question is whether these classes should be static nested classes or non-static nested classes(inner classes)?

I used non-static nested classes but IntelliJ IDEA suggests to make them static. According to the Hardcore Java book by Robert Simmons,

an inner class is instance-scoped and a static nested class is class-scoped.

As I understood in the Domain Driven Design, without an aggregate instance, it doesn’t make any sense to have domain events instances. This is the reason why I chose to go with non-static nested classes. Can someone explain this? Thanks.

Advertisement

Answer

The main difference between nested classes types
non-static nested class has full access to the members and methods of the class within which it is nested. It has reference to the outer class instance.
static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.

So if we will define Domain Event as a non-static nested class it will have full access to the instance of Aggregate. This violates the main Domain Event characteristics.

Immutability
Domain Event must be immutable, attaching the whole Aggregate state violates immutability. It should not have the whole state of the concept, only the copy of contextual information that might be useful for someone who subscribes to this event.

Domain Event doesn’t have business logic
Besides Aggregate can encapsulate business constraints. If Domain Event has an instance of aggregate, it has access to the business logic.

As result, we need to use only static nested class.

Please note Domain Events may be consumed by the local, and foreign, Bounded Contexts, but Aggregate is limited by one context. In this case, better move Domain Events to a separate class. There may be exclusions Bounded contexts sharing a same aggregate

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement