Wednesday, December 10, 2014

Bus of Doom

In a previous Bacon blog post a way to structure Bacon application was outlined. It introduces Buses as a central way to glue components with each other. I'm in a very strong disagreement with the proposed style. Why?
Subjects are the "mutable variables" of the Rx world and in most cases you do not need them.
In Bacon parlance that would be
Buses are the "mutable variables" of the Bacon world and in most cases you do not need them.
Now, that needs an explanation. We can split the statement to two parts and treat each individually. "Why Buses (and mutable variables) are bad", then "why you don't usually need them".

Problems with Bus

There was a time when data structures in our programs were built by mutating those data structures. In case you have entered this field only recently you may be a lucky one and haven't seen that madness in full glory (== spaghetti).
var cart = ShoppingCart()
var view = ShoppingCartView()
view.cart = cart
This was a bad idea as it creates temporal dependencies all over the program, making it difficult to locally understand how a piece of code works. Instead, a global view on a program is required. Who mutates what and when. It also created many bugs as components of a system are from time to time in an invalid state. Most common invalid state being at a construction phase where fields are initialized to nulls. A whole slew of bugs were eliminated and sanity regained by moving to immutable data.
var cart = ShoppingCart()
var view = ShoppingCartView(cart)
Ok, what does all that have to do with Buses? Well, Buses introduce similar temporal dependencies to your program. Is that component ready to be used? I don't know, did you plug its Buses already with this and that?
var shoppingCartBus = new Bacon.Bus()
$.ajax('/api/cart').done(cart => shoppingCartBus.push(cart))
...
shoppingCartBus.onValue(cart => renderCart(cart))
Here's a recent bug (simplified from a real world app) found in our company's internal chat. Can you spot it?
There's a chance that the ajax call on line 2 returns before line 4 is executed, thus the event is completely missed. It is temporal dependencies like that which are nearly impossible to understand in a bigger context. And what's worse, these bugs are difficult to reproduce as we are programming in a setting where stuff is nondeterministic (timers, delays, network calls etc.). I'm sure that many Bus fetished programs contain subtle bugs like above.

How to avoid Buses

I'll give examples of techniques avoiding Buses by refactoring the example in the previous blog post.
The first one is simple and obvious. Turn inputs of a component to be input arguments of the component.
Before:
function ShoppingCart(initialContents) {
  var addBus = new Bacon.Bus()
  var removeBus = new Bacon.Bus()
  var contentsProperty = Bacon.update(initialContents,
    addBus, function(contents, newItem) { return contents.concat(newItem) },
    removeBus, function(contents, removedItem) { return _.remove(contents, removedItem) }
  )
  return {
    addBus: addBus,
    removeBus: removeBus,
    contentsProperty: contentsProperty
  }
}
After:
function ShoppingCart(initialContents, addItem, removeItem) {
  return Bacon.update(initialContents,
    addItem, function(contents, newItem) { return contents.concat(newItem) },
    removeItem, function(contents, removedItem) { return _.remove(contents, removedItem) }
  )
}
I'm pretty sure everyone agrees that the refactored version is simpler.
The next refactoring has to do with remove links. Each shopping cart item will have a link and clicking a link will remove the item from a cart. The refactored version of the ShoppingCart needs removeItemclick stream as a function argument, but the individual items are created dynamically as the user selects items. This can be solved by event delegation.
$('#shopping-cart').asEventStream('click', '.remove-item')
You can state just once and for all: here's a stream of clicks of every .remove-item link in the shopping cart, and of all the future .remove-item links that will appear in the shopping cart. That is fantastic. It's like, you put it there and there it is. Event delegation is such a god sent tool and my heart fills with joy every time I have a chance to use it. After that the click events must be associated with items. A canonical way to do it is with data attributes.
Now the sample program is Bus-free.
function ShoppingCart(initialContents, addItem, removeItem) {
  return Bacon.update(initialContents,
    addItem, function(contents, newItem) { return contents.concat(newItem) },
    removeItem, function(contents, removedItem) { return _.remove(contents, removedItem) }
  )
}

var removeItemStream = $('#shopping-cart').asEventStream('click', '.remove-item')
  .map(function(e) { return $(e.currentTarget).data('id') })
var newItemView = NewItemView()
var cart = ShoppingCart([], newItemView.newItemStream, removeItemStream)
var cartView = ShoppingCartView(cart)
All done? Not yet. removeItemStream is hanging there while it probably should be part ofShoppingCartView.
function ShoppingCartView(cart) {
  return {
    cartView: ...
    removeItemStream: $('#shopping-cart').asEventStream('click', '.remove-item')
      .map(function(e) { return $(e.currentTarget).data('id') })
}
Whoops, now we introduced a cyclic dependency between ShoppingCart and ShoppingCartView.
var cart = ShoppingCart(initialContents, addItem, removeItemStream)
var {removeItemStream} = ShoppingCartView(cart)
Cyclic dependency is often given as an example where Buses are needed. After all the hard work should we now reintroduce Buses?
Here a Bus can be used to break the cyclic dependency, just as a mutable variable would do if you will. But we have other options too. Why don't we factor the components so that the cyclic dependency completely disappears.
function RemoveItems(container) {
  return {
    view: ...
    removeItemStream: container.asEventStream('click', '.remove-item')
      .map(function(e) { return $(e.currentTarget).data('id') })
}

var viewContainer = $('#shopping-cart')
var removeItems = RemoveItems(viewContainer)
var cart = ShoppingCart(initialContents, addItem, removeItems.removeItemStream)
ShoppingCartView(viewContainer, cart, removeItems)
Similar factorings can be almost always used to break cyclic dependencies.

Conclusion

Avoid Buses. View those as mutable variables and you will understand the kinds of problems they create. By relating Buses to mutable variables gives you an intuition on how to avoid those in a first place.

Tuesday, December 2, 2014

Structuring Real-Life Applications

The Internet is full of smart peanut-size examples of how to solve X with "FRP" and Bacon.js. But how to organize a real-world size application? That's been asked once in a while and indeed I have an answer up in my sleeve. Don't take though that I'm saying this is the The Definitive Answer. I'm sure your own way is as good or better. Tell me about it!
I think there are some principles that you should apply to the design of any application though, like Single Reponsibility Principle and Separation of Concerns. Given that, your application should consist of components that are fairly independent of each others implementation details. I'd also like the components to communicate using some explicit signals instead of shared mutable state (nudge nudge Angular). For this purpose, I find the Bacon.js EventStreams andProperties quite handy.
So if a component needs to act when a triggering event occurs, why not give it an EventStream representing that event in its constructor. The EventStream is an abstraction for the event source, so the implementation of your component is does not depend on where the event originates from, meaning you can use a WebSocket message as well as a mouse click as the actual event source. Similarly, if you component needs to display or act on the state of something, why not give it a Property in its constructor.
When it comes to the outputs of a component, those can exposed as EventStreams and Properties in the component's public interface. In some cases it also makes sense to publish a Bus to allow plugging in event sources after component creation.
For example, a ShoppingCart model component might look like this.
function ShoppingCart(initialContents) {
  var addBus = new Bacon.Bus()
  var removeBus = new Bacon.Bus()
  var contentsProperty = Bacon.update(initialContents,
    addBus, function(contents, newItem) { return contents.concat(newItem) },
    removeBus, function(contents, removedItem) { return _.remove(contents, removedItem) }
  )
  return {
    addBus: addBus,
    removeBus: removeBus,
    contentsProperty: contentsProperty
  }    
}
Internally, the ShoppingCart contents are composed from an initial status and addBus and removeBus streams usingBacon.update.
The external interface of this component exposes the addBus and removeBus buses where you can plug external streams for adding and removing items. It also exposes the current contents of the cart as a Property.
Now you may define a view component that shows cart contents, using your favorite DOM manipulation technology, like virtual-dom:
function ShoppingCartView(contentsProperty) {
  function updateContentView(newContents) { /* omitted */ }
  contentsProperty.onValue(updateContentView)
}
And a component that can be used for adding stuff to your cart:
function NewItemView() {
  var $button, $nameField // JQuery objects
  var newItemProperty = Bacon.$.textFieldValue($nameField) // property containing the item being added
  var newItemClick = $button.asEventStream("click") // clicks on the "add to cart" button
  var newItemStream = newItemProperty.sampledBy(newItemClick)
  return {
    newItemStream: newItemStream
  }
}
And you can plug these guys together as follows.
var cart = ShoppingCart([])
var cartView = ShoppingCartView(cart.contentsProperty)
var newItemView = NewItemView()
cart.addBus.plug(newItemView.newItemStream)
So there you go!