What are the best ways to share information between modules?

help

I imagine this is a pretty common situation, but I've gotten very conflicting responses. In a MVC-ish structure, say that the controller is triggered and needs to share the updated data with some other parts of the application somehow. Feel free to assume that the data in question is quite simple, such as { width, height }.

There are a number of ways to do this:

Controller calls a method like setData in the /model/data.js module. Data module exports both setData and getData. When other modules need data, they can call getData.

Con: Data module is exporting more than one thing

Con: This is basically sharing global state, and global state should be avoided. (hopefully there is no asynchronous code that could result in a race condition bug)

Con (?): Modules that consume the data don't see how the stateful data they use is maintained - those interactions are all in a separate module.

I was recommended to use an EventEmitter instead: when the model data gets updated, a dataChange event is emitted, and all data consumers see the event and update their own module-internal state.

Con: Explicit reassignment is necessary in every consuming module, example:

let width;
dataEmitter.on('dataChange', (dataName, newValue) => {
  if (dataName === 'width') width = newValue;
});

Con (?): Data is now being stored in, say, 8 places around the application, and not just one - it's all fragmented and semi-superfluous now, though there's now no need to import (global) state anymore, so maybe that's just the natural result.

Another option someone suggested: keep all state in the data module only, and have the data module call every consuming module with the required data as a parameter

Con: Data module now has to manage pretty much all entry logic used by any module that consumes data - the data module would probably be doing way too many things at once

Another option, somewhat similar to the first: have the data module consume an EventEmitter triggered by the controller, and export only the data itself ({ width, height })

Con: Some think mutable exports should not be used - exporting a getter function instead, while identical in functionality, would make it more explicit


When I posted my issue to some people, I got all of these as possible responses, and many of them disagreed with each other. I'm not experienced with modules; I don't know enough to differentiate the good from the subjective from the bad.

I know responses will be opinionated, but: What is/are the best-practices solution(s)? Is there a better pattern than those described above? Are some of the above definitely bad choices? Figuring out the right way to do this seems fundamental to working with modules, but I haven't seen anything yet that goes into detail on this subject, and I feel like I can't continue writing modular code until I definitively figure this out. (Links, especially long ones, would be much appreciated)

Thank you!

Posted Mar 19, 2018, 6:05 AM UTC

45
zazapeta•

Hello,

we have two problems here:

  1. The first one, the problem known as 'the source of thruth'

  2. The second one, is known as 'invalid the cach'

Let's trying to understand and to fix each one separated :

  1. Source of thruth (WRITE side): we can reformulate it as 'from where and how my data has been modified ?'. The problem with shared data, is not on the 'read'. It is on the 'write'. A common solution is to provide a SINGLE manner to mutate the 'data' (said 'setState((prevState) => nextState)'). If you can modify the data where and how you want, you will finish with a 'unpredictable state of your data'. And unpredictable state finish on unpredictable behavior.

  2. Invalid the cach (or rerender your view) (READ side): The problem with the cach is to 'know when to invalidate it'. Or for the view, when to rerender. This the 'read' problem. A common solution is to provide a SINGLE manner to read the 'data' (said 'getState()'). Each time you call getState, you get your data. But the question, is when do you call 'getState()' ? In a game/canvas/frame base interface, is in an infinite loop while (true) getState(); easy. But in a wep app, when do you call 'getState()' each second ? each millisecond ?

The pattern that resolve this problem (when to read the new state) is known as 'Observer/Observable pattern'.

Note : All solution of state management are base on this pattern. Why ? Because this is the only one that resolve this problem.

So, what is the pattern : we can reduce it as : 'I have many Obervers that observe (listen) an 'Observable'. Each 'observer' will be uptated when 'observabable is updated'. Done.

Resume :

  • Store.observe : (observer) => Store.observers.push(observer)

  • Store.getState : () => Store.state

  • Store.setState : js (nextState) => Store.state = nextState; Store.update(); //how do you compute the nextState ?

  • Store.update : () => Store.observers.forEach((observer) => observer.update());

Note: observer.update is the contract that link Observer and observable.

Link wikipedia

P.S : If you want to practice, try to implement an Clock with this pattern ;)


All that said, REDUX is an elegant implementation of this pattern. EventEmitter is also an other implementation. And so on. They, all of them, implement this pattern in the underlying source.

Have fun,

Cheers !

4
[deleted]•

[deleted]

2
[deleted]•

[deleted]

1
raleighpoint•

Like everyone is saying, this is a general problem of state management which has been around for a while.

You should read up on the history of React/Flux/Redux and best practices (https://redux.js.org/faq/code-structure) also look into stuff like immutablejs.

People usually employ Observables (aka "reactive") and/or single source of truth with unidirectional data flow. For example, people use RxJs and Redux together and separately. Observables/EventEmitter-based approaches can get tricky to debug/test/reason about.

Even within these approaches there are lots of different patterns which have different tradeoffs, so what is the "right way", if there is such a thing, depends on the application.

2
atlimar•

Though not appropriate for every application, you can look into Redux (or the Flux pattern), for advanced state management.

1
CertainPerformanceOP•

I'm not trying to figure out how to get something that manages it for me, or anything advanced - I'm trying to figure out the fundamentals of the best way(s) to do it in vanilla JS myself, since that'll (hopefully) help me understand the why, which is a much more solid foundation.

1
atlimar•

Flux/Redux still seems like one of the best patterns to look into in that case. Your OP touches on some very basic state management ideas, and Redux is pretty much an advanced version of event-based state handling that can be combined with a publish / subscribe pattern, and the idea of a single global state store, and sticking to a one way data flow, and an extremely transparent way of detecting race condition issues (look into redux devtools).

It sounds like you have started understanding the downsides of some of the simplest patterns, and it is time for you to look into how to combine a variety of code patterns into a better way of managing state. The Redux source code is very small, and fairly easy to understand. I would recommend going to the Redux site and start looking into how it solves state management, and you can then apply what you learn to your current understanding of how to understand state management. It's a science that is far from solved.

I'm not suggesting that you use Redux, I am suggesting that you understand Redux and why it was designed the way it is. FWIW, all libraries are written in vanilla javascript, and you can always look into the source code and underlying patterns to understand why it has become a popular solution.

A javascript pattern that has a name (e.g. redux) is simply vanilla javascript that got popular. A mistake developers often make is to start using libraries or frameworks without understanding their underlying design patterns, the "vanilla" part, if you like.

5
tsuviper•

+

1