Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for when to use Pub/Sub vs Dependency Injection

In most modern JS frameworks, the best practice for loosely coupling your UI components is with some implementation of Pub / Sub.

The question I have is doesn't this make debugging, maintaining your app more difficult, whereas dependency injection could achieve the same result (loose coupling)?

For example, my component should open a dialog when clicked. This needs to happen or else the UI will appear broken. To me it seems more readable to have the component make an explicit call to some dialog service. In the wild, I see this problem solved more with pub sub, so maybe I am missing something.

When using both methods together, where is a good place to draw the line when something should fire an event or fulfill that action with an injected service?

like image 343
pbo Avatar asked Feb 15 '14 16:02

pbo


1 Answers

Pub-sub is great for application-wide events where the number of potential subscribers can vary or is unknown at the moment of raising an event.

Injection always sets the relation between two, sure, you can create decorators/composites and inject compound objects made of simple objects but it gets messy the moment you start to do it.

Take a tree and a list for example. When you click a node, the list should be rebuilt. Sounds like injection.

But then you realize that some nodes trigger other actions, headings are updated, processes are triggered in the background etc. Raising an event and handling it in many independent subscribers is just easier.

I would say that injection works great through layers, when you compose a view and a controller or a view and its backing storage. Pub-sub works great between objects in the same layer, for example different independent controllers exchange messages and react accordingly.

like image 100
Wiktor Zychla Avatar answered Oct 28 '22 03:10

Wiktor Zychla