mbostock/d3 — Issue #384: Assert preconditions in code
Author: poswald
Created: 2011-11-22 05:43:07+00:00
State: open

As a newcomer to d3, I keep finding instances where assumptions are being made by the code but are not documented clearly. As one example, I was using the `d3.nest` object and passing it into a `d3.layout.stack` object as the layers. It was breaking and since I had never used the stack before it took a while of me digging through the stack function ( https://github.com/mbostock/d3/blob/master/src/layout/stack.js#L10 ) to realize that the issue was that one of the series in my source data was missing an entry. This function (rightly) assumes that each series has the same number of values in the 2 diminutional array however that precondition isn't stated in the docs and when it fails it is deep in the iteration ( https://github.com/mbostock/d3/blob/master/src/layout/stack.js#L41 ) and the error is a bit cryptic. There are many instances where the code is dependent on certain other parameters being set. Usually it just returns undefined but in some cases like this, it will blow up.

One way to fix this is to document things better - which is certainly welcome - but a bit hard to maintain. Another way would be to assert preconditions at the beginning of the method. This would fail-fast, help to document the function to developers, and give the beginning user a better error message when it fails:

If you want to add an `assert()` function into the code somewhere, I would be willing to add them and send you pull requests as I hit these types of problems. The assert() could be a noop normally but then in development mode, it could be enabled to give better error output.

What do you think?