Syntastic

I love writing with vim, but, for many valid reasons, some people are averse to it. I think the steep (–ish) learning curve has something to do with it, but I think some people really don’t want to give up their IDE. The thing is, vim isn’t just a text editor. You can extend it to do pretty much anything, including features that normally show up in IDEs.

I recently started using syntastic, which is a vim plugin that runs linters or syntax checkers and displays warnings and errors right in your window. IDEs like Eclipse or Xcode provide this syntax-checking for a couple of languages, but syntastic supports many languages and linters out of the box with pluggable support for nearly any language.

Setup

If you use pathogen like every sane vim user does, installing syntastic is just like any other plugin. Clone the repository or create a submodule in bundle/syntastic and you’re ready to go.

I mainly work with Javascript, Python, HTML, and CSS, so that’s what I’ll talk about. It’s worth checking out the syntax checkers in bundle/syntastic/syntax_checkers/, even if you just look at the list of files there. You might have to dive into the files to figure out which linters are actually supported as it’s not clearly documented.

Before we get to configuring individual syntax checkers, syntastic itself has a couple of configuration options. Syntastic has what it refers to as a “mode map”, which is basically just a way to configure which file types are checked. Here is the relevant config option from my vimrc:

" On by default, turn it off for html
let g:syntastic_mode_map = { 'mode': 'active',
    \ 'active_filetypes': [],
    \ 'passive_filetypes': ['html'] }

The ‘mode’ option set to active means that syntastic is on by default, so we can leave the list of ‘active_filetypes’ empty. The ‘passive_filetypes’ names filetypes that syntastic does not attempt to check. I don’t check HTML files because I mainly work with templates that either can’t or won’t validate with most HTML syntax checkers. If templates use non-standard attributes, it’s hard for a syntax checker to do its job.

Python

Setting up syntastic for use with python was extremely easy. pyflakes has relatively sane defaults, so running it with no configuration is more than acceptable. Just install pyflakes with pip install pyflakes and syntastic will automatically do the rest.

Javascript

There are a number of Javascript linters, including JS Lint and Google’s Closure linter, but I decided to use the communtiy-driven JS Hint. JS Hint can be configured with a jshintrc, which just is a JSON object that contains options. There are two categories of options: those that enforce stricter rules than the defaults and those that relax default checks. The options page of the jshint website does a great job of explaining each option. You can view my jshintrc on my Github page. I added a few “enforcing” options, but the only “relaxing” option I use is the “sub” option, which allows subscript notation when accessing properties, e.g. this['domNode'] as well as this.domNode.

Usage

syntastic and underscore.js

By default, syntastic runs your file through the configured filetype’s linter whenever the buffer is written. If there are errors, they are highlighted inline. When your cursor is on a line with an error, the description of the error is visible in the status line. You can use the :Errors command to open a quickfix window with a list of all errors in the file. Pressing enter on an error will take you to that line in the file. Syntastic uses vim’s signs, which means that a gutter with a sign appears on the left side of every line with an error on it, making it easy to scan the buffer for errors.

You can configure syntastic in many other ways, including telling it to check a buffer whenever it is opened. I explored the help file (:help syntastic) when I first started using syntastic, and it was incredibly helpful. I encourage anyone who uses syntastic to do the same.

Syntastic has already helped me avoid many typos and silly errors that would ordinarily be hard to track down. It’s an invaluable tool in my workflow.


Mint

Mint

I just started using Mint to track statistics on my site. I’ve been using Google Analytics for a long time, and I will continue to do so, but it is definitely geared more towards sites trying to earn money. Mint seemed to offer a more streamlined and customizable interface for people who just want to look at stats.

Mint is a pluggable, extensible stats system. Mint modules are known as “peppers,” and each one provides some small functionality. There is a default pepper that provides some basic stats functionality like page views, unique visitors, search terms that brought those visitors to your site, and which pages they are looking at. There are a large number of official and community peppers over at the Peppermill that offer much more functionality and statistical views.

Installation

Installing Mint was a breeze. I just followed the simple instructions and I was good to go. If you have unfettered access to your server (via ssh) you should have no issues.

Issues with mod_pagespeed

I did run into a couple strange display issues when I went to view my Mint stats. Each pane took up the maximum width when it was opened. Even though I could view all my stats, the interface didn’t look good. After posting in the forum and fruitlessly trying to edit the Mint source code, I disabled mod_pagespeed on the hunch that my code changes weren’t taking effect because mod_pagespeed was caching everything. All of a sudden, the Mint interface looked fine, and it turned out that my small tweaks didn’t really make much of a difference after all. I still haven’t figured out exactly why mod_pagespeed was causing issues, but disabling it sure did fix them. If anyone has any insight into this, please let me know.

Peppers

I mentioned that Mint is pluggable and extensible. In fact, that is its entire basis: every bit of functionality is provided by modular plugins called peppers. Mint comes with the default pepper that I mentioned before, but there are many more available. I use a number of them.

Backup/Restore

This pepper is self-explanatory: back up and restore your Mint stats. That’s it.

iPhone

The default Mint interface isn’t that great for a smaller screen like the iPhone, so this pepper displays an optimized interface when you view Mint on an iPhone.

Outbound

A lot of analytics apps try to show you where your visitors come from, and that information is important. You might be interested in where your visitors go next, so this pepper shows your most popular outbound links.

User Agent 007

This cleverly-named pepper shows a breakdown of your visitors by user agent.

Real Estate

This one shows a breakdown of your visitors by the size of their screen.

Local Searches

If your blogging software has a search mechanism, this pepper shows you what your visitors are searching for. Note that this is different than the search engine queries that bring visitors to your site that the default pepper shows.

Doorbell

When you’re viewing your Mint interface, the doorbell pepper provides a some audio feedback when you get a new visitor.

Errors

This pepper shows any error pages that your visitors may have seen, along with the page that was requested that caused that error.

Locations

This pepper provides a breakdown of your visitors by geographic location.

Sparks!

Sparklines provide a great way to view useful trends in a small space. This combined with the iPhone pepper makes checking visitor trends on the go a snap.

I use both Google analytics and Mint on my site, but I find myself looking at Mint much, much more often. It just offers a better view into the kind of people visiting your site, especially if you’re coming from a position of trying to understand what kind of content brings them to your site in the first place. Mint comes highly recommended.


The Handle Pattern

I’m not entirely sure if there’s a better name for this pattern that already exists, but I like “handle pattern” to describe this method of keeping track of and managing “subscriptions”.


var subscriber = (function() {
    
    var _listeners = {};
        
    var s = {
        // Listen to a channel and call a callback when that channel fires
        listen: function(channel, cb) {
            // Add the callback to the list of listeners on the given channel
            _listeners[channel] = _listeners[channel] || [];
            _listeners[channel].push(cb);
            
            return {
                // Return an object that can be used to remove the callback from the channel
                unlisten: function() {
                    // Remove the callback from the list of listeners on that channel
                    _listeners[channel].splice(_listeners[channel].indexOf(cb), 1);
                }
            }
        },
        
        // Manually fire events on a given channel.
        publish: function(channel) {
            _listeners[channel] = _listeners[channel] || [];
            _listeners[channel].forEach(function(cb) {
                cb();
            });
        }
    };
    
    return s;
})();
    
var h = subscriber.listen('update', function() {
    console.log('The update event was fired!');
});

subscriber.publish('update'); // > "The update event was fired!"

h.unlisten();
    
subscriber.publish('update'); // > <no output>

When you have an event-driven application, like a Javascript app that performs actions based on user interaction or based on back end “pushes” to a listening front end, you often have a central “publisher” that handles firing events when certain actions occur. It makes sense to have a static listen function that takes a “channel” and a callback function to call when that channel gets updated. The problem comes when you have to decide how to stop listening to that channel. If you go with a static unlisten function on the publisher with the same signature as listen (the channel and callback), you need to keep track of which callback is listening to which channel, and it can get messy.

Instead, listen can return a handle, which is just an object that contains a method unlisten that knows exactly how to stop listening on the specific channel and with the specific callback that was given to listen. Then, the caller just needs to keep track of the return values of listen (as opposed to the arguments to listen) in order to be able to unlisten later.

The Dojo Stateful interface uses this pattern to watch values on objects. If you watch a property, a callback can be fired each time that property changes. The return value of watch is a handle that can be used to stop watching that particular property value.

Feel free to play around with this code on JSFiddle.


Don’t Commit FIXME or TODO


function getObject($id) {
    $object = null;
        
    // TODO Do we need to validate username?
    $objects = $this->db->retrieveForUsername($this->username);
        
    // FIXME Write `retrieveForIdAndUsername` instead of iterating here
    foreach ($objects as $o) {
        if ($o->id() == $id) {
            $object = $o;
            break;
        }
    }
        
    return $object;
}

This shouldn’t happen. I’m not talking about the comically bad code – it’s a contrived example, but it proves the point – but about the little “notes” left by whoever committed this.

Do we need to validate the username? Probably. Find out, and take the necessary action. If you know your codebase well, it should take about ten seconds to know the answer.

The FIXME is a bit more time-consuming, but the payoff is greater. If you leave this FIXME, I’m going to assume one of two things: you’re a lazy programmer, or you’re a bad programmer. You’re lazy because you can’t be bothered to write something correctly or you’re bad because you don’t know how to write it correctly. 1

Of course, use TODO or FIXME while you’re developing to keep a list of tasks that you have to finish before your feature is complete. Just don’t commit them to where other developers can see them and certainly don’t merge them to trunk.

If you’re lazy with that code now, there’s no way you’re going to overcome that laziness and come back to fix it later.


  1. One could argue that being aware of bad code is better than nothing, but that’s fluffy. If you’re aware of a problem, you’re probably smart enough to do something about it. 


Microwave Ovens Suck

Really. My microwave helpfully makes the numbers 1 through 6 shortcuts for running for that number of minutes, on full power. When’s the last time you needed to microwave something for six whole minutes?

Most of my microwaving involves re-heating leftovers or softening things like tortillas or butter. These things don’t take minutes; they take seconds. And if I have something that really need to warm up over the course of one or two minutes, it certainly doesn’t need to be that long at full power. Those preset buttons are absolutely useless. I need presets for 10, 20, and 30 seconds, and maybe 90, and at power levels of 5, 7, and “hi”. Not “high”, mind you, “hi”.

The rest of my microwaving time is spent trying to defrost frozen meat, like a chicken breast or a tilapia filet. There’s a button for this, yes, but it requires that I guess the weight of the thing I’m defrosting. I don’t own a kitchen scale, but even if I did, I sure as hell wouldn’t bust it out to figure out how to long I need to defrost my meat. Let me tell you what I’m defrosting, and then figure out how long to defrost it. Defrosting is not a new science or even science at all.

Here’s another irksome feature: when I open the microwave door before the timer goes off, I really appreciate that it remembers how much time was left. Once eight hours have passed, though, I think it’s safe to assume that I’m no longer in need of that timer. “PRESS START” is not helpful after that long. Show me the clock again after a reasonable amount of time has passed.

Another thing: that awful beeping sound. I know some smug person with too much time on his hands has Googled his unit’s manual and has memorized the arcane sequence of button presses required to mute the microwave, but I haven’t. Why is there not just a mute button? It’s not for lack of room: put it under my “9 ” button or in between “Defrost” and “Popcorn” (which always burns those poor defenseless kernels) or even in the place of the “Reminder” button, because I don’t keep my todo list on my microwave.

Can someone “Nest-ify” the microwave? I would buy one in a heartbeat.