I don't like events as an API / programming is not Lego; it's Tetris
Related: https://www.johndcook.com/blog/2011/02/03/lego-blocks-and-organ-transplants/
- Some people advocate web components as application architecture
- Often contrasted to React
- Core idea: hierarchy of components
- Components communicate with child- and parent-components. The latter, in React, usually happens through callbacks.
- In Web Components, the answer is usually events.
- No, plain events thrown to a parent component are practically callbacks, but without making the connection explicit. Fine.
- However, I don't like events that bubble up - in other words, events that might, theoretically, be handled anywhere in your application - or worse, someone else's application.
- Basically, an event is an API contract: I throw an event with these properties, so you can handle it. When there's a parent-child relationship, it's clear who that contract is between.
- However, if an event might be caught anywhere up the tree, or thrown anywhere down the tree, we have a potential source of bugs. There's a risk in removing or changing the expected parameters of an event handler, because any component down the tree might rely on that behaviour. Likewise with removing or changing thrown events: there might be something up the tree relying on the current structure.
- In other words: you should treat that API as immutable. Which is not a problem in itself: keeping a stable API facilitates loose coupling. If you can rely on an API remaining the same, you can replace the parts on either side of it safely.
- However: if the smallest parts of your application are loosely coupled, then you can only replace them by parts that behave exactly the same. At that point, the loose coupling doesn't buy you anything.
- The trick of proper architecture is drawing the API boundaries there where you expect least changes to be necessary in the future - which is why understanding business requirements is such an essential part of coming up with a software architecture.
- And in fact this is often heralded as the selling point of web components: it's like lego! All you need to do is stack components on top of each other to compose an application!
- But this relies on the fallacy that the component level is the proper place to draw the API boundaries. It's not. Sometimes a set of components just belong together; when I have a set of
<li>
s I want them to be contained inside a list. Sometimes specific components rely on some piece of global state - e.g. the user's login status, and you can't just drop them into components that represent that global state in a different way. - So no, they can never be like lego. You can't just stuff any block onto any others, only some types of blocks onto some types of other blocks. It's more like Tetris, in that sense, and proper architecture is doing your best to make the blocks fit together, based on what you expect future blocks to look like.
Edited by Vincent