How is an Express Router Like a Banjo?

We left off yesterday with a Banjo implementation that was basically a dumb pass-through to the implementation of BanjoString. Here's why:

For Christmas, my wife got me a banjo mute. I'm not going to read too much into her motivation for that gift. It looks like a heavy-duty metal hairclip with felt padding on the inside edges. You clip it to the bridge (the piece of wood near your picking hand that holds the strings up) and it quiets the instrument by dampening the vibrations before they reach the head and the resonator (the round part of the banjo)

So you can see as we add complexity and detail to our application, that the behaviors of the strings and the banjo continue to diverge. To model this, I can add a muted property to the banjo, and then alter the properties of the emitted tone after it's returned from string's pick method, but before it's returned from the banjo's pickString method.

(The web version has better code formatting)

class Banjo {
  muted = false
  strings = [/* unchanged */]

  fretString(stringIndex, fret) {/* unchanged */}

  pickString(stringIndex, strength) {
    const tone = this.strings[stringIndex].pick(strength)
    return {
      // if muted, cut volume in half
      volume: this.muted ? tone.volume/2 : tone.volume,

Notice that the BanjoString class remains unchanged, because we're not changing the behavior of the string. We're adding properties and behaviors to the Banjo.

If you're familiar with Express, Rails, or really any other modern web server framework, the Banjo is conceptually starting resemble a router or controller. It's combining the inputs from the user (frets and picks), applying them to a consistent model (the BanjoString), and transforming the results before returning. We're basically mimicking the request/response pattern, where the request is the combination of frets and picks, and the response is the resulting tone.

Tomorrow: Broken Strings!

Did you like this?

I send a daily email with tips and ideas like this one. Join the party!