What's a good design pattern for bidirectional signals/events?

Design pattern for bidirectional signals/events

  • This problem feels rather basic, yet I've never known a great solution. I'm looking for a way for components in an application to notify each other while being as decoupled as possible (both at build/compile and run time), but also avoiding circular notifications in a way that components do not need to self-mitigate against. I happen to be hitting this issue (for the hundredth time) in JavaScript right now, but that is incidental. Some means of decoupling include: Dependency injection (DI). In this case I use require.js which allows, for instance, substituting mock implementations in unit tests by creating alternate require.config() setups. Event dispatching. E.g. fooInstance.listen('action string', barInstance.actionHandler) Publish/subscribe (aka pub/sub). The last two are basically variants of the Observer pattern with different pros and cons. The problem I want to solve is not specifically addressed by these patterns, and I'm not sure if its an implementation detail or if there is a pattern to apply: fooObj sends a message (fires an event, whatever) that the "baz" property has changed barObj.bazChanged() handles this event by calling its own setBaz() method barObj.setBaz() fires an event that "baz" has changed fooObj.bazChanged() handles this event ... As a real case, imagine fooObj is a GUI component, with a slider for "tempo", and barObj is a music sequencing component that plays back a score. The slider should affect the tempo of the sequencer, but the score can contain tempo changes so when playing the sequencer should affect the slider position. A solution should be modeless. One approach is to add guards, for example: function handleTempoChanged(tempo) { if (this.tempo == tempo) return; ... } This works but feels like a poor solution because it means every event handler needs to either assume it needs a guard, which is ugly boilerplate and often not required, OR needs to be aware of the other components in the system that would make a cycle possible. Arguably, this point is wrong, guards should always be used if the handler is going to fire a changed event directly or indirectly, but this still feels like boilerplate logic. This may be the only answer to my question... Is there general case pattern to deal with potential cycles as described? Note that this is not about synchronous vs. asynchronous; either way the cycles can occur. EDITED to reflect insight from commenters: I realize it is possible to eliminate the boilerplate, using some sort of mixin. In pseudo-code: class ObservablePropsMixin: // generic setter with gaurd function set(propName, value): if this[propName] = value: return this[propName] = value _fire(propName, value) // generic method to add listeners function observe(propName, handler): _observers[propName].add(handler) // private event dispatching method function _fire(propName, value): foreach observer in _observers[propName]: observer.call(propName, value) ... This is simplified to focus on my question, but a real mixin would implement other pubsub or event or signal semantics, analogous to any event dispatcher implementation. Components needing to be observers or observables would inherit/extend from the mixin (the above assumes some form of multiple or aggregate inheritance is possible in the language. This could be modified to work with composition instead, e.g. ObservableMixin.constructor(observedObject) rather than using "this".

  • Answer:

    The general solution to avoid repeating boilerplate is to pull it out into its own class. In this case, you would usually create a Publisher class that handles avoiding cycles for you. var tempoPublisher = new NumericPublisher(); tempoPublisher.onTempoChange(moveTempoSliderWidget); tempoPublisher.onTempoChange(changeSequencerTempo); tempoSliderWidget.onSlide(function (percentage) { tempoPublisher.publish(percentage * maxTempo); }); In your NumericPublisher.publish() you put your guard. Then no matter how many NumericPublishers or components you create, you only need the guard in one place. This also breaks the dependencies of the components on each other. They only need to know about the tempoPublisher, which can be injected using DI.

Jason Boyd at Programmers Visit the source

Was this solution helpful to you?

Other answers

A number of years ago, I had a similar problem in real time system design. The general approach I took was to create a set of modules with each module having a number of facets: inputs, outputs, control, maintenance, repository and a couple of others. Each module was assigned to a level in the system -- sometimes the level was fairly arbitrary. In some cases, a module was split into parts, with lower level functions separated from higher level functions. In other cases, the facets were broken into levels (higher level inputs versus lower level inputs). We established rules for how call-backs could be handled. The rules were based on directionality (up/down, left/right) and facets (inputs could only be connected to outputs). Rules were expressed as "this type of marble can only ever roll downhill" or "this ball can bounce higher". Model-View-Controller has a set of rules that are similar. In addition, within the JSP environment, there are timing rules: certain observations can only be made at certain times. The MVC framework itself imposes the rules. In your case, it sounds like you are trying to build the framework yourself. Thus, you must establish the syntax and semantics of your "observer language". Here is one approach you might want to play with: Establish kinds of observations. The kinds are based on the impact of the observer on the state of the system. Establish relationships between kinds. a) Display kind (View in MVC). The observed value is only ever formatted for viewing, and the value goes in only a single direction (towards the user, or towards a printed report). b) Calculation kind. The observed value will take part in a calculation, likely with other observed values, and the result may, in turn, be observed. Circularity abounds and there must be infrastructure to identify convergence or divergence. c) Input kind. User input such as form field or drop down. Result goes inward, towards the heart of the application. Display and Input kinds can be composed, of course, but they have a state relationship that prevents vicious circles. d) Validater kind. Observes one or more values and rings a bell when things aren't right. Inputs and Validaters can be composed, again with state and timing relationships ... By establishing a protocol or language or rules of engagement, you may be able to retain your sanity. :)

BobDalgleish

The guards are only possible solution. There is no way some 3rd party code could distinguish between loop in event chain and normal event chain. While the guards might seem as boilerplate logic, they are actually quite simple to implement some kinds of them can be abstracted away if language supports it. For example onChange could automatically check if the value changed and only fire the event if the value changes.

Euphoric

This is just a brief idea. I have not used or tested it myself. In addition to a guard based on comparison of the current and the new value, circular notifications could be prevented by this scheme: When a handler originates a property change, it asks the system for a unique event ID, and associate this property change with the event ID. When another handler receives this property change, if it finds necessary to issue further property changes, it must "chain" the additional property changes with the original event ID, as well as attaching new event IDs to each additional property change. Thus, the event IDs will form a tree, with the original event at the root. Each handler can store the event IDs it had finished processing, and thus prevent double-processing. In some cases, a similar effect could be achieved by using a timestamp instead of a unique ID. Note that this is a very heavy-weight option. I have not actually tested or used it, so it might not work as I had wished.

rwong

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.