Program state synchronization

Almost every app has dependencies in its state, when one subset of the state depends on another subset. For example, when you type your Twitter update, a label on the right shows the number of free symbols left:


The free symbol count label (with text "127") depends on the textbox content. Every time the dependency state changes, the dependent state may need to be updated. That's why the symbol count changes while you are typing.

The problem, however, is that synchronizing state may be difficult when dependencies are more complex. There may be more than one dependency:


Whenever any of order line costs changes, the total cost must be updated. It means that it should listen to changes in every order line object.

Finally dependencies may change over time. If a new order line is added, the total cost label must subscribe to its change notifications; when it is removed, the subscription must be disposed.

Dependent state must be always synchronized with its dependencies, but it is not always easy to do.

Current solution: data binding

There are partial solutions to this problem. The most obvious one is WPF/Silverlight data binding, but it has some disadvantages/limitations:
  1. It is verbose in non-trivial cases. In our Twitter example you can't simply bind the label to the textbox's free symbol count. In such cases you have to define a custom value converter, which is verbose and type-unsafe. The same applies to MultiBinding that cannot work without a value converter.
  2. It doesn't work with dynamically changing dependencies. If a new order line is added, you have to manually update your MultiBinding. Why can't it update itself automatically?
  3. It requires your class to be inherited from DependencyObject, and it can't be used at all in assemblies that must not depend on WindowsBase.dll.
Standard data binding is painful to use in non-trivial cases.

Bad solution: manual code

The other option is to manually update the dependent state using event handling, but it is:
  1. Verbose, since you need a method per event in the worst case.
  2. Error-prone, because you have to track all dependencies and not to forget to subscribe to all needed events.
  3. Complex, when state dependencies change over time.

Last edited Feb 14, 2011 at 8:59 PM by reactive, version 4


No comments yet.