6

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".

2
  • I'm not sure I fully agree that this question is off-topic, but given that you're using engineer jargon that computer scientists tend not to use, I think this question would be better off in an engineering venue than here in a computer science venue. So I'm migrating this question to where I think it'll be better received. It would help if you said what language you're programming in. Commented Mar 5, 2014 at 23:55
  • Thanks @Gilles. I wasn't sure about where to ask; this looks like the better place.
    – Jason Boyd
    Commented Mar 6, 2014 at 2:23

4 Answers 4

2

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.

1
  • Apparently I'm not yet able to upvote answers to my own question... I think this is a good answer. I realize if my classes used a mixin for pub/sub or signal/slots or whatever, that property change listeners could generically gaurd the property. As a side benefit such an approach would provide clearer code and runtime introspectable understanding of which properties respond to or send change events.
    – Jason Boyd
    Commented Mar 6, 2014 at 19:36
1

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. :)

4
  • 1
    That all sounds more complicated than what I'm asking. See my example of the tempo slider. In that case, it legitimately is a user input (so would feed into the heart of the system as you put it) that also would be updated by the application. It's a 2-way user input, like a slider on a hardware mixer board. I can add a guard to prevent cycles, but I just wish there were a pattern to apply more generally. It sounds like you're describing an architectural approach based on convention, which is maybe the only answer, but I posted the question in case there is a common pattern that applies.
    – Jason Boyd
    Commented Mar 6, 2014 at 2:55
  • 1
    The pattern I'm describing is that different kinds of observers have different relationships with each other. By enforcing those relationships, you can simplify many of them, and only need to add infrastructure (circularity management, e.g.) for some of them. Commented Mar 6, 2014 at 2:58
  • 1
    Got it. But okay, for those that do need circularity management, is there any way better than each component gaurding against redundant properties being set? I have a feeling I'm asking for something magic.
    – Jason Boyd
    Commented Mar 6, 2014 at 3:03
  • 1
    You can create a generalized circularity manager. It maintains a set of tuples, periodically flushing them at transaction end. It stashes (observer, item) pairs and gives permission to proceed only if the pair doesn't exist in the set. The "transaction end" is a boundary that is natural to your application cycle. As I suggested for the "calculation kind", you might want to allow cycles as long as convergence is happening. Commented Mar 6, 2014 at 15:04
1

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.

1
  • 1
    same comment I made above. You're right.
    – Jason Boyd
    Commented Mar 6, 2014 at 19:37
1

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.

1
  • 1
    I thought about something like this. My main issue is that because it would almost have to be implemented behind the scenes (e.g. by the pub/sub service or a mixin or superclass) it would border on magic. Client code implementors might, for instance, take for granted the behavior without understanding how it works, and therefore not know why making multiple calls to setFoo(value) with the same value still results in multiple change events being fired. Still, this approach sounds like it could work for some applications.
    – Jason Boyd
    Commented Mar 7, 2014 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.