Ruby Scrubbing JavaScript: Raise Those Curly Braces

Of the Programmer Holy Wars, “curly braces on the same line, or the next line?” is not as vitriolic as emacs/vim or tabs/spaces, but it’s up there.

(Personally, I don’t care. I’ve done years with each style. You get used to it.)

In JavaScript, it’s less of an issue, because, when you put curly braces on the next line, JavaScript will (sometimes) automatically insert semicolons into your code. It’s well-documented and discussed, and understandable; here’s a question about it on stackoverflow.

Yesterday I reviewed some old JavaScript (circa 2007) that our web designer Daniel rehabilitated, and this concern came up. Rather than hunt around manually for dangling curly braces, I wrote some ruby to find and fix them.

# fix-js-curies.rb
ARGV.each do |filename|
  src = File.read(filename)

  # This multi-line regex looks for any { that
  # comes after a \n, and any tabs or spaces,
  # and replaces it with a space and a {.
  new_src = src.gsub(/\n[ \t]*\{/m, ' {')

  if src == new_src
    puts filename
  else
    puts "#{filename} fixed!"
    File.open(filename, 'w') do |f|
      f.puts new_src
    end
  end
end

You can pass it any .js files as command-line arguments:

$ ruby fix-js-curlies.rb app/assets/*.js

Props to Daniel: when I ran my script, it didn’t actually find any, because he got them all ahead of me.

Direct Manipulation, and Text Editors

Hat-tip to Giles Bowkett for mentioning Bret Victor’s talk, Stop Drawing Dead Fish, about direct manipulation and computer interaction as a tool for illustrators and animators.

I paused this video part-way through, so I could Get Down to Work. I paused it around 34:30, right after Bret Victor mentioned David Hestenes‘ idea that algebra and geometry help us model the world in similar ways, but that algebra uses our linguistic ability, while geometry uses our visual/spatial perception. Victor went on to say that tools for visual artists should use our visual/spatial abilities (direct manipulation), rather than our linguistic ones (code).

Like I said, it was time to Get Down to Work. I flipped over to Sublime Text 2, where I happened to have a block of text selected. Warming up, I idly hit command-I to search for a bit of text, only to realize that Sublime was only searching in that selected text. This is handy! I’ve been wanting something like this lately, when a method or variable name shows up all over the file, but I’m only working on one method.

Using the trackpad to select a bunch of text, and then working on it, feels a lot like I’m holding the text in one hand, and working on it with Sublime in the other. I discovered this accidentally, too – I’ve felt pretty productive with Sublime after the (tiny) initial bump, and I occasionally, gradually, get better as I learn new tricks.

I switched to Sublime after trying to learn Vim for a month or so. I’d been an emacs user for a few years, but I was under-using it, and didn’t need all the extra machinery. Vim seemed lighter, so I tried it out. But it felt like learning emacs all over again, but with different incantations: everything forced into the keyboard. And I get that! I’m a home-row Dvorak typist! But I still felt like emacs and vim were a step back from humbler tools like Programmer’s Notepad.

Bret Victor’s talk suggests an interesting explanation for that. He points out that some animations are a pain to create manually, and some behaviors are hard to code into the tool: so you divide and allocate tasks to the computer and the artist according to their abilities, and their cooperation produces the best effect.

Maybe this explains the appeal of these less-hardcore text editors. Sure, using the mouse and buttons for everything, a la Microsoft Word, is tedious, but so is forcing all interaction through the keyboard. Maybe a better allocation of tasks, a better balance of responsibilities between typist and tool, is what’s needed.

Out of Love with Active Record

(I’m a new-comer to Rails. When I first found Ruby, and Rails, I liked the Ruby better. And I never found many Rails jobs near home anyway. So for years, Ruby flavored my C#, and C# is where I learned, among other things, to persist my domain aggregates with NHibernate. Now I’m a card-carrying Rails jobber, which is great, because I play with Ruby all day. And the Rails community is discovering domain-driven design, and ORMs…)

Steve Klabnik just posted about resisting the urge to factor your models into behavior-in-a-mixin and dumb-persistence-with-active-record. He nails it when he says:

Whenever we refactor, we have to consider what we’re using to evaluate that our refactoring has been successful. For me, the default is complexity. That is, any refactoring I’m doing is trying to reduce complexity… One good way that I think about complexity on an individual object level [is its] ‘attack surface.’ We call this ‘encapsulation’ in object oriented software design.

If you learn only one thing from his post, let it be that “mixins do not really reduce the complexity of your objects.” Greg Brown threw me when he said that mixins are just another form of inheritance, and I think he was getting at the same thing.

Steve’s suggestion for separating persistence and behavior is to – duh, once you see it – separate them into different classes: a Post and a PostMapper, or a Post and a PostRepository. When I used C# and NHibernate, we loaded our Posts from the PostRepository, which used our PostMapper for data access. (Actually, our PostMapper was an XML mapping file.) You might call that overkill, but in a legacy app, it was nice to sheetrock our repositories over all the different data access technologies we’d acquired over the years, from the shiny new ORM to the crusty old Strongly-Typed DataSets.

When I was on that team, the thing that we worried about was, what grain should we build our repositories at? We didn’t have simple models, we had domain aggregates: we’d load a ThirdPartyAdministrator, which had many Clients, which each had a number of Accounts of different types, each of which had different options and sub-objects. So, what kind of repositories should we build, and what methods should they have? If we want to load the Client’s Accounts, should we load the ThirdPartyAdministrator, find the Client, and get its Accounts? load the Accounts directly? load the Client, and get its Accounts?

For a ridiculously simplified example, but to give you the flavor of it, say we load the ThirdPartyAdministrator, the aggregate root, and go from there:

class ThirdPartyAdministratorRepository
  def load_tpa(id)
    ...
  end
end

tpa = ThirdPartyAdministratorRepositor.load_tpa(42)
client = tpa.clients[client_id]
accounts = client.accounts

That’s too coarse; do we really have to load the TPA before we can get the client we’re after?

class ClientRepository
  def load_client(id)
    ...
  end
end

class AccountRepository
  def load_account(id)
    ...
  end
end

client = ClientRepository.load_client(client_id)
accounts = client.account_ids.map { |id|
  AccountRepository.load_account(id)
}

That’s too fine a grain, too low-level; we don’t want to have to muck around with Account IDs.

client = ClientRepository.load_client(client_id)
accounts = client.accounts

That might be a good middle-approach.

It comes down to knowing your application’s data-access patterns, and your domain’s constraints. If you often need a chunk of data, all together, you should probably have a repository for it. If one piece of data depends on another, your repository probably shouldn’t make you get them separately.

With Rails’ ActiveRecord, all this is sorted out for you – you define your associations, it provides all those querying methods, and you use the correct ones for what you need. With repositories, you have decisions to make – you have to design it, and design is choice. But choosing is work! and you can choose inconsistently! sometimes, it even makes sense to! I’m curious to see how the Rails community, with its culture of convention, tackles this. And for myself, I plan to check out DataMapper at some point.

Book Review: Pragmatic Thinking and Learning

I was planning on reading Andy Hunt’s Pragmatic Thinking and Learning: Refactor Your Wetware for a while, but kept putting it off, thinking it wasn’t really central to what I’m interested in, what I’m doing.  I was wrong.

People have different skill levels, from novice to expert.  One sign of expertise is the ability to intuit solutions not available through linear thinking.  Intuition happens on the right side of the brain, so we need to use the right side more effectively.  Rather than “left brain” and “right brain”, he calls them “L-mode” and “R-mode”, for “linear” and “rich”, to emphasize that it’s not literally two halves of your brain working differently, but two different modes of thinking.  Most of the book is about using R-mode more, and using L-mode appropriately, to fact-check your R-mode.

It draws on psychology, neurobiology, cognition studies, managing, teaching, the arts, product design, and math.  The bibliography is ten pages long, and I’ve got a bunch of them highlighted for my next evening at the bookstore.

The most valuable changes I’ve made since finishing the book are:

– Be ready when your R-mode strikes. Since “querying” the R-mode can take a long time, we run it asynchronously, and we never know when the results will come in.  (This explains the “ah-ha!” moments in the shower, on the drive home, and when you’re falling asleep.)  So keep a notebook handy for writing things down.  I’m writing in a notebook almost daily (I’ve joined the cult of moleskine), writing down ideas as they come up.  It’s also a tider home for all the scraps of paper that have lived in my wallet for years, ideas scrawled and smudged into them.  And I’m on my 4th or 5th pocket mod.

– Maintain your ‘exo-cortex,’ your external memory. I wrote a mini-wiki engine with Sinatra, and so far, I’ve used it for everything from clojure, to saving quotes, to robot rights.  I wrote it for practice, but it’s nice to have a searchable, non-linear notebook.

The book mentions Gerald Weinberg’s fieldstone method of writing: to build a stone wall, you gradually gather stones from the field as you clear it, and pile them up.  When you have enough, build your wall.  Both the wiki and the notebook serve this purpose.

– Map out your thinking, and doodle. Drawing pictures engages your R-mode, making it more active, helping you make connections, and understand more clearly.  Besides, it’s fun. This is my 3rd time learning emacs, and it’s finally sticking — I think it’s mostly because I drew up a cheat-sheet, pictorially explaining each command’s effect.  I also map out my learning and career goals this way.

emacs cheat sheet

One of my favorite parts is, after you’ve mapped something out, and the drawing looks like a pile of yarn, re-draw it on a clean sheet, fixing up all the awkward placements and messy bits.  The benefit of this second version is in its creation — by considering how to re-organize it, you’re thinking more about the problem, in ways you might not have before.  This works for note-taking, too.

– Take advantage of your brain’s plasticity. You can change how your brain works by believing it works differently: make it smarter, more creative, cheerier.  This is a pretty incredible claim, but he cites two books I’d like to check out.  It sounds impossible, but I’ve seen it work on me, to some extent.  My biggest problem is continuing to believe it works.

Some things I have yet to try:

– Take a walk.  A meditative walk, like around a labyrinth.

– Write morning pages: for three weeks, as soon as you wake, write down three pages of text.  It doesn’t have to be anything specific.  The idea is, right after we wake, our R-mode is more active, so the gems will be more accessible, and they’ll pop out onto the page.  I’m more curious to see what I come up with.

– I have to get better at setting SMART goals: specific, measurable, achievable, relevant, and time-boxed.  I’ve never been much for this kind of discipline — I made a few, but didn’t stick to them, and haven’t gotten into the habit yet.  But like the book says, change is hard:

Change is always harder than it looks — that’s a physical reality, not just an aphorism. An old, ingrained habit makes the equivalent of a neural highway in your brain. These old habits don’t go away. You can make new neural highways alongside, going a different route and making short-cuts, but the old highways remain. They are always there for you to revert to—to fall back on. Practice may not make perfect, but it sure makes permanent.

Working Faster, Avoiding the Mouse

I’m moving away from my mouse all the time. On the one hand, it’s so much faster to keep my fingers in the same place, and on the other, it’s easier to automate keystrokes than mouse motions & clicks. I especially don’t like mousing through menus, so I’m always on the lookout for keyboard shortcuts. Here are two tools that help me stay away from the mouse.

SlickRun

SlickRun is an application launcher: a special keystroke brings up a small pseudo-command-line window, you type in a command, and it launches the associated application. By default, it uses a tiny window, but I made mine use an 18pt font, right in the middle of the screen — it’s my main focus when I use it, and it disappears right after. When it first pops up, I have it display the date & time.

You can type in URLs, and it launches them in the default browser. It includes the Ctrl+Enter shortcut, so “google” + Ctrl+Enter launches “http://www.google.com”, just like in Firefox and IE. You can type in file paths, and it helps you with tab completion.

You define “magic words”, short names for applications, so “mail” launches Outlook, “ffox” for Firefox, etc. But long, descriptive magic words are no problem, because it auto-completes them for you. I can launch “editor_programmers_notepad” with only “ed”.

Magic words can take parameters too. Here, the magic word “release” opens explorer to a network share where my team stores release information, each release in its own folder. The magic word uses the release name to create the path, and launches explorer.

SlickRun can export and import its list of magic words, which is great, because I move between three computers regularly. If you’re curious, you can import my magic words.

SlickRun comes with Jot, which is a pop-up notepad for short-term notes. It’s kind of strange, coupling this with a launcher. I never really use it, but if you have a use for it, it’s there.

I’ve used SlickRun for about a year, and at this point, I don’t think I could live without a launcher. I’m thinking of trying Launchy, which looks very promising.

StExBar

StExBar is an add-in for Windows Explorer that I found on the wiki for The Productive Programmer. It creates hot-key shortcuts for common actions: Ctrl+Shift+N creates a new folder, Ctrl+M opens a command prompt in the current folder, Ctrl+Shift+C copies the full paths of selected files, Ctrl+Shift+R renames files in the current folder with regular expressions. This is really nice — it shows the current file name on the left, and the new on the right, based on the pattern you typed in. You know exactly how the rename will work before you run it.

It also lets you define custom commands. So far, I have Ctrl+E opening the file for editing in Programmer’s Notepad, Shift+U running svn update on the selected items, and Ctrl+B opening a cygwin bash shell in the current folder.  UPDATE: I just added Ctrl+Shift+D for running a diff.

I just installed StExBar three days ago, so it’s not ingrained into my fingers yet, but I already missed it at home this weekend.  It fills a narrow spot, adding hotkeys to Explorer, but it does it really well.