Break stuff. Now.

Mutable Broadcasted Objects

What you can do to prevent code from unwantedly mutating data

October 14, 2014

This time, I'll go technical with JavaScript. I've been too long since I have posted a technical article, and delved too much about random ramblings of the mind. This time, I'll deal with an outstanding problem I have been facing for like a week now which deals with broadcasted mutable objects.

Pub-sub and all the other names they call it

Pub-sub (aka: broadcast-listen, etc.) is a method of decoupling pieces of code by having them announce their data through a "broker" library as well as subscribe to the data. This way, dependencies are reduced (to the broker library) and have pieces of code not directly interact with each other. This avoids breakage when let's say one piece of the code is taken out.

The case of mutability

The problem I face here is that the data is in a broadcast. Anyone subscribed gets the same exact data, and by "same exact", I mean the same exact object. So if say I had a LOADED_DATA event for a store whose data is an array of fruits and let's just say 10 separate modules are subscribed, if LOADED_DATA were to fire, all 10 modules get a reference to that same array.

Now what if one of those 10 modules were to accidentally modify the data, chances are, some of the remaining 9 modules will get the mutated data instead of the original data. Seems like a small problem, but when you have an application that uses the same data, it's so easy to be tempted to manipulate the data.

What we can do

Just don't do anything with the data

Well, that's one thing. If the data comes from the storage layer to the view layer, all you have to do is just render and nothing else. However, if you happen to have a view library that does 2-way binding that seeps into the data, then that's another story. That brings us to the next defensive measure called...

Defensive cloning

The most obvious solution is to just clone the broadcasted data before meddling with it. It can either be cloned per subscriber or have the subscribing code do it themselves (hopefully the do). But the most obvious solution turns out to be the most expensive solution. When you have deeply nested data or just have a flat array of 10k items lying around, this is not really good.

Immutable data

Another way to do it is to turn the broadcasted data immutable. In JavaScript, this can be done with a recursive Object.freeze. However, this means that data needs to be copied over since you can't alter the data anymore, unless you are just going to render the data.


There's pros and cons. For sure no library has ever made such move since they tend to go for performance, or just not care at all and deem it as "out of scope" or "won't fix". Oh well, moar research work.