Why people use message/event buses in their code? [closed]

I am considering using a In memory Event Bus for my regular java code and my rationale is as follows

Each object in the system can listen to each message, and I think it’s
bad, it breaks the Encapsulation principle (each object knows about
everything)

I am not sure if this is really true, I class needs to register with the event bus to start with, similar to observer pattern, Once a class has registered with the Event Bus, only the methods which have the appropriate signature and annotation are notified.

and Single Responsibility principle (eg when some object needs to a
new type of message, event bus often needs to be changed for example
to add a new Listener class or a new method in the Listener class).

I totally disagree with

event bus often needs to be changed

The event bus is never changed

I agree with

add a new Listener class or a new method in the Listener class

How does this break SRP ?, I can have a BookEventListener which subscribes to all events pertaining to my Book Entity, and yes I can add methods to this class but still this class is cohesive …

Why I plan to use it ? It helps me model the “when” of my domain ….

Usually we hear some thing like send a mail “when” book is purchased

we go write down

book.purchase();
sendEmail()

Then we are told add a audit log when a book is purchased , we go to the above snippet

book.purchase();
sendEmail();
**auditBook();**

Right there OCP violated

I Prefer

book.purchase();
EventBus.raiseEvent(bookPurchasedEvent);

Then keep adding handlers as needed Open for Extension Closed for Modification

Thanks

Leave a Comment