scotthmurray / d3-book

Code examples for “Interactive Data Visualization for the Web”
http://d3book.com
Other
2.41k stars 1.79k forks source link

Indentation style for method chaining #1

Closed nautat closed 7 years ago

nautat commented 11 years ago

Nice work Scott!

I noticed you don't use Mike's indentation style for method chaining. Was that a deliberate choice? I've always found this style very useful and educational. It makes it very clear on which selection the methods are operating.

And maybe even more importantly; when you store the results of a chain in a variable, this indentation style makes it very clear what selection you are actually storing. With complex chains that for example involve enter() and several child appends, it very quickly can get confusing and therefore it is better to be very explicit.

In short, I think this indentation style makes the code much more readable and understandable; especially for beginners.

See the the selections chapter in Mike's workshop:

With method chaining, I normally use four spaces to indent. However, I use two spaces for operations that change the selection, such as append. This causes operations that change the context to stick out. In this snippet, the entire expression evaluates to the appended h1 elements, even though we started by selecting

elements.

var h1 = d3.selectAll("section")
    .style("background", "steelblue")
  .append("h1")
    .text("Hello!")

Use caution with method chaining: append returns a new selection!

scotthmurray commented 11 years ago

Thanks! I’ve gone back and forth on this, as I actually found the indentation style more confusing when I was just getting started. So for the book (and the sample code here), I abandoned it. But I see your (and Mike's) point, as once the concept of changing selections along the chain is understood, this indentation is helpful. I just didn't want to confuse the matter further, and wanted to keep the code as simple as possible to read.

You may have just convinced me otherwise, though. Let me revisit this and see how spacing could be addressed clearly in the book text.

scotthmurray commented 7 years ago

Following up on this, as I'm working on the 2nd edition now…

In the end, I agree with you about the value of Mike's indentation style. In practice, however, I'm not confident in the publishing platform's ability to maintain spacing accurately across all formats (print, ePub, Kindle, web). Given that, I don't want to risk committing to a more nuanced indentation convention, as it could backfire and actually be less readable (or more confusing) to people if the formatting doesn't come through as intended.

Thank you for this good suggestion, however!