Random Code 4

:: CodeCritic, Programming Languages

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  , slide: function (type, next) {
      var $active = this.$element.find('.active')
        , $next = next || $active[type]()
        , isCycling = this.interval
        , direction = type == 'next' ? 'left' : 'right'
        , fallback  = type == 'next' ? 'first' : 'last'
        , that = this

      this.sliding = true

      isCycling && this.pause()

      $next = $next.length ? $next : this.$element.find('.item')[fallback]()

      if ($next.hasClass('active')) return

      if (!$.support.transition && this.$element.hasClass('slide')) {
        this.$element.trigger('slide')
        $active.removeClass('active')
        $next.addClass('active')
        this.sliding = false
        this.$element.trigger('slid')
      } else {
        $next.addClass(type)
        $next[0].offsetWidth // force reflow
        $active.addClass(direction)
        $next.addClass(direction)
        this.$element.trigger('slide')
        this.$element.one($.support.transition.end, function () {
          $next.removeClass([type, direction].join(' ')).addClass('active')
          $active.removeClass(['active', direction].join(' '))
          that.sliding = false
          setTimeout(function () { that.$element.trigger('slid') }, 0)
        })
      }

Ah, JavaScript. How I love and hate thee at the same time.

This random snippet of code comes from twitter’s “bootstrap” repo on GitHub, the most forked repo in the most popular language on GitHub.

First, there’s a complete and total lack of comments here. That could be because this file is automatically generated, but I’m pretty sure that’s not the case. I think instead that it indicates that just about everyone regards JS as a quick-and-dirty hack language.

You’ll also see no semicolons in this code, despite the fact that they’re allowed and frankly, an extremely good idea. This is another indicator that the author of this code wasn’t really writing for the ages.

So, what’s going on in this code?

Well, I’ve now talked this one to death in class, so I’m not all that interested in dissecting it after the fact, but I will point out that this code looks quite fragile to me, aside from the fact that of course it’s terrifyingly fragile just by virtue of being written in JavaScript.

In particular, it seems to be interacting with a whole bunch of state-based things, without a lot of thought about their possible interactions. I could be wrong.

One giant red flag is the reflow that’s triggered through simple observation of the width. That’s a DOM thing, though, not a JS thing.