Creative Confidence

The more skilled I become in programming the less I think that confidence in one’s abilities is gained through practice and the more I believe it is innate. There are few brilliantly creative coders out there (notably Why, and Jeremy Ashkenas) who don’t care whether their code meets your standard and just produce awesomely cool tools.

I have always quietly admired these people (and others like them). In fact I’m writing now in an effort to be more like them. But the point is that the kind of confidence they have appears to be innate.

I don’t believe they ever woke up one day, looked around and thought “now I am good enough.” Instead they are the kind of people who always walked their own path, doing what they thought was cool.

Right now, right here I challenge you to do the same.

Write some sort of small app. If you don’t feel like testing it, then don’t. If you want to write it all in one class, go for it. Stop criticizing your ideas and just run with the next one you have. Let it flow. Don’t even pause long enough to think whether the idea is a good one. Just go ahead and implement. Do this with every idea you have and in no time you will be one of the most prolific developers out there.

For a long time I have secretly held all software developers to the same standard: you are not a real programmer until you have made something that is your own invention. This is been a secret because I don’t meet my own measure.

Except now I do.

Zenburn Background Color in OS X Terminal

At work they say I’m a little OCD. I don’t like it the desks are askew, I need the center of my keyboard to line up with the center of my monitor (specifically the little Apple logo), and I mouse left handed to keep the balance with the numeric keypad on my right side. I’m not dysfunctional (so we can drop the O from OCD, I suppose) but I have a definite aesthetic I am comfortable with.

This aesthetic extends to my screen real estate, too. I always have my terminal windows semi-transparent so I can see the text on webpages I’m looking at through the terminal window. This way I can try little programming experiments in real-time while reading about them on a web page. I only recently found out that I could do that with MacVim. To set transparency on MacVim (or gVim) add the following to your .vimrc file.

if has("gui_running")
    set transparency=20
endif

Once I had my terminal and Vim windows both semi-transparent I was immediately bothered by the fact that they were two different shades. Crazy, I know, but that’s just the way I am. So this morning I took the time to match up the colors exactly. It turns out that the (Zenburn)[http://slinky.imukuppi.org/zenburnpage/ “Zenburn Colorscheme for MacVim and gVim”] background color is matched exactly in terminal by setting your window background color to RGB 48, 48, 48.

If anyone else out there has this particular fetish then I hope you find this useful. If not then this note should work wonders for me in the future. :)

Random Rails Memory Settings with RVM

At work we recently started using parallel_tests. Overall it’s a pretty cool project. If you don’t know, it’s a project that parallelizes running tests across all cores and on all CPUs.

One of the things we struggled with while using parallel_tests was memory tuning. On an eight-core system it is very easy to start swapping to disk. Since the point of running your tests in parallel is to get them done with quickly, swapping to disk is obviously bad.

Matters get further complicated when you have to switch from one project to another, each with different memory requirements. One of our projects uses approximately 150mb per test run just to get Ruby and Rails started. A new Rails 3 project takes just a fraction of that to load up. Multiply the larger figure by eight cores, add the overhead of running other apps and eight gigs of ram can quickly run out.

Apparently we don’t want to use the same memory configuration for each project. Enter RVM. Ruby Version Manager allows you to use different gemsets per project. By configuring your .rvmrc in your project directory, arbitrary commands are executed when you cd into your project root. Here’s my .rvmrc for my larger project.

rvm ree@my-project
# Ruby Enterprise Edition test-specific memory configs
export RUBY_HEAP_MIN_SLOTS=250000
export RUBY_HEAP_SLOTS_INCREMENT=250000
export RUBY_HEAP_SLOTS_GROWTH_FACTOR=1
export RUBY_GC_MALLOC_LIMIT=250000000
export RUBY_HEAP_FREE_MIN=25000

This memory configuration will be loaded whenever I cd into my larger project root. That means that when I run my tests the above memory settings will be used. On my smaller project I tweak these memory settings to be more generous.

Hat tip to Bryan Liles and BJ Clark for the original memory config and idea respectively.

Object Oriented Design Revisited

A couple of weeks ago a coworker and I were talking about writing small game sims. I’ve never really written a game before, having spent my whole career in IT. This conversation was inspirational because the requirements were so simple: implement a board game with two AI players.

My initial design was to model the entire universe of a game. I chose Mancala since it is a two player game with a pretty simple setup (unlike chess). In Mancala there are two players, a board composed of houses and a store, and score tokens (called “seeds”). Each player controls the seeds in their houses, and gets points for having seeds in their houses and store. As each player takes a turn they must move the seeds around the board and eventually into their opponent’s side of the board, thus unfortunately giving away points.

Models

  • Player
  • Board
  • Game

The problem with this model became quickly apparent: the board doesn’t do anything by itself. It is not really a first-class citizen in the game basically being used by the players to store their seeds. While it seems like the kind of thing that should be an object at first glance there just isn’t much for the board to do.

Things got worse when I considered two players taking turns sharing the board. Now not only does the board need to know how to handle itself, but it needs to know who is asking in order to perform the correct action. Alternately, the Player would need to know about the innards of the board and manipulate those elements directly, thus demoting the board by violating its encapsulation.

After a few more tries with tweaks to the design I settled on a model design where the Player had a Town with Houses and a Store in it. The Town was the player’s half of the playing board and knew how to shuffle seeds around as needed. I could have kept the Town as only a struct since the Player that owns the Town is the only one to manipulate it, but I decided to break it out since the town deals with shuttling seeds around while they player deals with playing. This way the player could issue commands to the Town (perhaps better named as DeliveryBoy) while presenting an interface for the other player for when it came time to pass seeds to their opponent.

Models

  • Player
  • Town
  • Game

Even the Game class is almost superfluous in this situation. I really only wrote it to start the game and print out information.

Apparently not all nouns in the modelled universe needs to be a model in the program universe. In the verbs-and-nouns game that serves as a starting point for the model but it is by no means the end point. When modeling a system you have to consider what I call the active nouns; the things that actually do something. The inactive nouns (such as the playing board) are more likely structures that get manipulated by other entities, or at best provide an interface for manipulating themselves. As you should be able to see even in this trivial example, the real world does not necessarily map one-to-one with the program world.

The most fun I had doing this project was when I got to use the strategy pattern on something that actually uses strategies. Object oriented programming is a natural fit for writing a game simulation. So many problems that people try to solve using object oriented application design methods fail because the problem domain is not object oriented. I’ll have to write more about that another time.

The Game

Here you can see the Town class. Its pretty simple. It knows how to give insight into its status and performa a couple simple actions.

module Mancala
  NUMBER_OF_HOUSES = 6 
  STARTING_SEEDS_PER_HOUSE = 4

  class Town
    attr_reader :store, :houses

    def initialize
      @store = 0
      @houses = Array.new NUMBER_OF_HOUSES, STARTING_SEEDS_PER_HOUSE
    end

    def number_of_seeds_in_houses
      return @houses.reduce(0) { |counted_seeds, seeds_in_house| counted_seeds + seeds_in_house }
    end

    def take_seeds_from address
      seeds = @houses[address]
      @houses[address] =  0
      seeds
    end

    def count_seeds_at address
      @houses[address]
    end

    def deliver_seed_to address
      @houses[address] += 1
    end

    def deliver_seeds_to_houses_starting_with address, seeds_to_deliver
      (address...NUMBER_OF_HOUSES).each do |house|
        return 0 if seeds_to_deliver == 0
        deliver_seed_to house
        seeds_to_deliver -= 1
      end
      seeds_to_deliver
    end

    def deliver_seed_to_store seeds
      return 0 if seeds == 0
      @store += 1
      seeds - 1
    end
  end

The Player is also pretty simple. His main job is to communicate with the other player and take his turn.

class Player
    attr_accessor :opponent, :name, :town, :strategy

    def initialize name, strategy
      @town = Town.new
      @name = name
      @strategy = strategy
    end

    def pick_a_house
      Strategies.send @strategy, @town
    end

    def score
      @town.store + @town.number_of_seeds_in_houses
    end

    def can_play?
      @town.number_of_seeds_in_houses > 0
    end

    def deliver_seeds_to_houses seeds_to_deliver
      @town.deliver_seeds_to_houses_starting_with 0, seeds_to_deliver
    end

    def get_starting_addresses
      address = pick_a_house
      [address, address + 1]
    end

    def take_turn
      address, next_address = get_starting_addresses
      seeds = @town.take_seeds_from address
      while seeds > 0
        seeds = @town.deliver_seeds_to_houses_starting_with next_address, seeds
        was_last_seed = seeds == 1
        seeds = @town.deliver_seed_to_store seeds
        if was_last_seed and can_play?
          # Bonus turn!
          take_turn
          return
        end
        seeds = opponent.deliver_seeds_to_houses seeds
        seeds = deliver_seeds_to_houses seeds
      end
    end
  end

This is the Player’s brain. The game can be started with the player using any of these strategies. Each one is a way of picking the house the player wants to move seeds from.

module Strategies
    def self.get_addresses_with_seeds town
      valid_addresses = []
      (0...NUMBER_OF_HOUSES).each do |address|
        valid_addresses << address if (town.count_seeds_at address) > 0
      end
      valid_addresses
    end

    def self.random_house town
      valid_addresses = get_addresses_with_seeds town
      valid_addresses[rand(valid_addresses.length - 1)]
    end

    def self.closest_house town
      valid_addresses = get_addresses_with_seeds town
      valid_addresses[0]
    end

    def self.furthest_house town
      valid_addresses = get_addresses_with_seeds town
      valid_addresses[-1]
    end
  end

And here is the Game itself. As I said before, this class is basically optional. I used it to visualize the game as the two AI players took their turns.

class Game

    def initialize
      @one = Player.new 'Player one', :furthest_house
      @two = Player.new 'Player two', :furthest_house

      @one.opponent = @two
      @two.opponent = @one
    end

    def print_time duration
      puts 'The game lasted ' + duration.to_s
    end

    def print_score
      winner = @one.score > @two.score ? @one : @two
      if @one.score == @two.score
        puts 'The game was a TIE!'
        return
      end
      puts "#{@one.name} using strategy #{@one.strategy} has #{@one.score} points!"
      puts "#{@two.name} using strategy #{@two.strategy} has #{@two.score} points!"
      puts "#{winner.name} is the winner! The better strategy is #{winner.strategy}" 
    end

    def print_board
      puts "   #{@one.town.houses.inspect} #{@one.town.store} = #{@one.score}"
      puts "#{@one.town.store} #{@two.town.houses.reverse.inspect}    = #{@two.score}"
    end

    def play
      while @one.can_play? and @two.can_play?
        @one.take_turn
        @two.take_turn
      end
      print_score
    end
  end
end

And here’s an easy way to make the whole thing run.

if __FILE__ == $0
  run = 30
  puts "Running the game #{run} times"
  start = Time.now
  run.times do
    Mancala::Game.new.play
  end
  puts (Time.now - start).to_s
end

From the command line.

$ ruby mancala.rb

A Simple Web Server in Clojure

I’ve been messing around with Clojure lately and really enjoying the language. Just for fun I decided to put together an incredibly simple web server. Here’s how it works.

The first thing we need to do is import some sockets and stream handling. The sockets allow us to open up a port on the our computer (called a socket) and listen on it for incoming connections from our web browser. The reader and writer classes are a convenient way to read the input from the socket and respond. This easy import is thanks to the wonderful JVM and all the libraries that are written for it.

(import '(java.net ServerSocket SocketException)
        '(java.io PrintWriter BufferedReader InputStreamReader))

Next up we define functions (defn in Clojure semantics) to create readers and writers that will listen and respond on our socket. Functions in Clojure start with an open parenthesis and the keyword defn (defn followed by an optional comment and a list parameters between square brackets [ arg1 arg2 ] (technically the Vector data structure) and finishes up with a list of Clojure commands. Like so:

(defn get-reader
  "This optional comment is where I explain what this method does. 
   In this case it creates a reader that will listen on our web server's port."
  [client]
  (new BufferedReader (new InputStreamReader (. client getInputStream))))

(defn get-writer
  "Creates a writer to write out data to our web client, probably a browser."
  [client]
  (new PrintWriter (. client getOutputStream)))

(defn create-socket
  "A nice semantic wrapper for creating a socket on the specified port."
  [port]
  (new ServerSocket port))

Here’s the fun part of our server. This is where the server accepts the incoming connection and hands the input and output handlers off to the service we provide. Our listen-and-respond function takes a socket and the service function that we will let handle our web requests (see below). Since we don’t know which service we are going to be handed, only that the service needs our server input and output streams to communicate to the outside world we just call it “service” in our parameter list. When it is time for the service to do its job we pass it the resources it needs and let it rip!

(defn listen-and-respond [server-socket service]
  (let [client (. server-socket accept)
        input  (get-reader client)
        output (get-writer client)]
    (service input output)))

Here is where the server actually runs, hence the name run-server. This is a loop that will continue as long as our server socket is open. Our server dutifully monitors the socket waiting for an incoming connection. Any connection that comes in will get sent off to listen-and-respond. Once the response has been sent our server goes back to spinning its wheels waiting for another connection.

In both this function and the previous one we use the keyword let. let creates variables that only exist within this function (local variables) and cannot be reassigned. You can think of them as constants if you like.

(defn run-server [port service]
  (let [server-socket (create-socket port)]
    (while (not (. server-socket isClosed))
      (listen-and-respond server-socket service))))

The last thing we need to do is write the service we will be providing. We could do anything here, all the way up to serving large web app if we liked. Since I am interested in writing a web server (and not interested in implementing the HTTP spec) I just wrote a simple echo function. The function reads in all the data from the socket and spits it back out.

You might notice that our echo service uses def instead of let. Unlike let, def allows us to redefine the value of a local variable. This is useful here while we are looping since the last value we read in tells us when to stop listening and close our connection.

(defn echo [input output]
  (def line nil)
  (while (not (= line ""))
    (def line (. input readLine))
    (. output println line)
    (. output flush))
  (. output close))

To run our new server we put this as the last line of our Clojure file. This line calls our run-server method with a port to listen on and the actual service function that will be invoked.

(run-server 3456 echo)

If you put all the code in this blog into a file on your computer (assuming you have Clojure properly setup) then you can start the server up, point your webserver at localhost:3456 and see the result. To start the server make your way to a command window type in the line below (without the dollar sign). To stop your server press control+c.

$ clj simple-web-server.clj

This super simple server doesn’t serve up files, that would require writing up a more complicated service. It also only handles one connection at a time. To make this server handle multiple connections simultaneously we could you Java threads, or we could do the cool thing and use Clojure Agents. Enjoy!

Handy Rails Greps

At work we develop on Rails using Cucumber and RSpec. I personally use Vim for editing which means I don’t have cool features like “find in project.” The thing is, I don’t need them, I just use grep instead. That said I noticed I was writing the same two greps several times per day. Here they are:

gild() {
  egrep -Rn "$1" "$2" | egrep -v "\.git|Binary|log/|\.log|db/|vendor/|tmp/"
}

gilds() {
  egrep -Rn "$1" "$2" | egrep -v "\.git|Binary|log/|\.log|db/|vendor/|tmp/|_spec|features/"
}

Gild and gilds are mnemonics for grepping without Git, binary files, logs, database files, and specs or features. Just copy and paste them into your .profile and you’ll be all set for Rails greppy goodness.

UPDATE: Made them faster and more legible with better use of grep.

How to Interview (a Programmer)

Over the last few weeks I have been interviewing for a full-time position at just the right type of company. I’m glad to say that I’ll be joining Goldstar Events in March. Of the companies that I interviewed with, Goldstar gave me the best experience by far.

I’ve spent quite a bit of time on both sides of the interview table. Obviously the advice here is geared toward interviewing a programmer, but much of the advice would work well for any creative type. Here are a few things that make an interview fantastic for the candidate.

Don’t Be Messy

This may be obvious (like many of the things in this list) but it bears repeating: you never get a second chance at a first impression. If you want to hire someone, you have to look decent. You needn’t be impeccable since most of the power sits on your side of the negotiating table but if you are trying to attract top talent then you need to show them that you have some standards. Nobody will want to work in a company that is chaotic or for a boss that smells.

Don’t Be Late

I remember at one interview I had to wait thirty minutes for the interviewer to arrive. I was literally walking out the door when he came back from a long lunch. Needless to say, things didn’t go well. Just as you want the candidate to show their respect for you by being on time and prepared, you need to do the same. It would have taken an amazing company to make up for an interviewer being seriously late to the interview.

Be Prepared

You should expect an interviewee to have extra copies of their resume for you, and they expect you to have read it before you sit down. I’ll bring extra copies of my resume to an interview, but you should already be familiar with what is on it. If you don’t know who I am or what I have done, why am I here?

Google (verb)

One of the first things I do when I find an interesting candidate is google them. I want to see what kind of online persona they have. Do they have a github account? What about a blog?

One time I was researching a candidate and came across some highly charged political posts she had made. Online she was a fierce debater and had no problem going head-to-head with other people. I was very reassured when she was the epitome of politeness in the interview room. By seeing both sides of her personality I had a kind of character reference and felt I knew her better than I would otherwise.

A word of caution though: you cannot decide not to hire someone based on what you find on google. It may be technically legal but you are inviting trouble if you do this.

Be Cool and Use Small Talk

Most of the nervous energy will be coming from the interviewee. One of your jobs is to be calm and help them get calm, too. Start by asking how their day has been, talk about the weather, discuss any bland and boring topic you feel like just to get the other person talking. A five to ten minute ice breaking session can make the difference between a successful and failed interview.

Prepare your Pitch

Many times employers assume that the candidate already knows everything about their company. While any good candidate will know the general information about your company you should be prepared to let them know what makes you awesome. Maybe you think that the team you are on is the brightest bunch of people on the planet. Maybe your company does something that genuinely makes you proud. Keep that thing in mind and share it with the candidate. At the end of the day, people do things they want to do. Make them want to join your team.

Start with a Softball

Any time you are asking about domain knowledge start off super-easy. Maybe have them write a simple loop in their favorite programming language. Maybe you could have the candidate complete the fizz-buzz problem. The reason you toss them such a soft-ball is not to see if they can code, but to see if they can code while terrified. (Interviews are nerve-wracking, remember?)

Deep Dive

Here’s where most interviews start to go off track. You need to see if the candidate has what it takes. Do they know what they are talking about? If they program on the web, do they understand HTTP? Do they know design patterns? What do they think of design patterns? Have they done agile coding? What do they think of agile? This is the time for you to ask open-ended questions where the candidate either shows how awesome they are, or digs a horribly deep hole. This is also the time for you to stop talking.

Get Hand-On

The single most important part of an interview, and the part that literally 90% of of the companies I have interviewed with did not do is code. That’s it. Have the candidate actually write some code.

I think the best way to do this is to have a problem you know well and then pair program with them to find the issue. Another good approach is to have them help you fix a minor bug. Perhaps you could mix the two by intentionally adding a bug.

This part of the interview shows you how good the candidate is at reading and writing code. That is, how good they are at the thing they will spend the majority of their time doing.

I always feel disappointed when the company does not make me code during an interview.

Take Your Time

The interview process is a time when you really need to get to know each other. Ideally you could have the candidate contract on-site for a week to see how they perform. Short of that luxury you need the interview to last for a few hours. I’d say four hours is a good amount of time.

Many people are upbeat and positive during the interview and show only their best side. It’s like a date. Nobody can keep on their best behavior for four hours straight. That would be one long performance.

Taking your time not only lets you get to know the real person behind the persona, but it also gives you ample time to ask follow up questions and those things you always forget to ask before they leave. Of course, let the candidate know how long they will be hanging out for. You also might want to buy them lunch.

Be Candid

I usually keep my opinion to my self about the candidate during the interview but I’m beginning to reconsider. During my interview at Goldstar I got “extra ponints” for using vim instead of emacs. This feedback really bolstered my confidence and made me feel good about the team. There’s nothing wrong with letting the candidate know how well they are doing in the interview, just don’t be weird about it.

Say Goodbye

The last impression a candidate has of your team will be the one that sticks. If you really like them but ditch them at the end of the interview they will have a bad feeling about taking the job. Make sure that you smile, shake hands, and escort the candidate to the door. Protocols vary from business to business and the candidate may have forgotten the way out after a four-hour long interview. Make sure to end on a high note.

In the end whether or not a candidate is right is up to you. I wrote this just to help programmers get to know each other. I hope you find it useful.

Taught Not To

Alan Perlis wrote “Everyone can be taught to sculpt: Michelangelo would have had to be taught how not to. So it is with the great programmers.”

I spent ten hours coding the other day and it was one of the best days I have had in a while. I sat down at 10am after sleeping in and didn’t leave my desk without the intent to return until 10pm, when I went to bed. None of the code I wrote was earthshaking or new. There were no novel ideas expressed, but I would like to think that what I made was of near the highest quality.

This got me thinking about the above quote. There are a few ways it could be interpreted but I think it means that Michelangelo could sculpt all day and feel good about the day. I don’t think it means that everything Michelangelo made was brilliant (although it may have been) rather that the practice of sculpting is something that would have had to be trained out of him.

Metaprogramming Ruby Book Review

Most programming books that I read are good, but only a few are noteworthy. Metaprogramming Ruby: Program Like the Pros is an unusually insightful and approachable book. It came out last year but I’ve only now gotten around to reading it.

The book kicks off with a pretty normal introduction to metaprogramming and some possible scenarios where you might find you need metaprogramming. Through out the whole text the author Paolo Perrotta keeps the kid gloves on and talks you through each topic. This is nice for people who are new to the material and can be easily skimmed by those who are looking to brush up or expand their existing knowledge.

Paolo smartly divides each of the main chapters into day sized chapters. I found that each chapter in this book was just about the right length. I had a hard time finishing each one in a single sitting but not so hard that I couldn’t manage it. Although Metaprogramming weighs in at 267 pages the meat is really in the first 180 pages or so.

Without giving away too much, I must say that Metaprogramming is the kind of book that will take your Ruby skills to the next level. The insights into the Ruby object model, how methods work, recipes on changing variable scoping, and a very brief introduction to DSLs will delight the average Rubyist while simultaneously guiding them into the skills needed to be an expert.

All this praise does not mean that the book is without flaws. Some of the thinking in the book is a little simplistic. In one instance we are told to create some code in a module, but the examples start us writing classes and methods. It seems like even a novice programmer would have started by following the explicit instructions provided.

Quibbles aside this is an excellent book and one that I might even recommend as an introductory text to Ruby for someone who is already a highly skilled programmer in another dynamic language. Metaprogramming in Ruby is a great read.

4.5/5 stars

Function Currying in JavaScript

Since I promised to write something about function currying here it is. Also, I realize that Scheme may not be the most approachable language so this time I’ll be using Javascript: Lisp in C’s clothing.

Function currying is the process we used to make thunks a couple of posts ago. The thing is that you needn’t create a thunk every time you curry a function. In fact you could define different functions dynamically based on application state at different times to service different types of request.

Lets say you have to search for an album in a record store (think music, not databases), and the search strategy might change depending on the circumstances. One search strategy is the binary search. This is way cooler than a standard linear search. However, there are times when you might choose one over the other.

function linearSearch(album, store) {
    ...
}

function binarySearch(album, store) {
    ...
}

Now if we wanted to allow for the dynamic selection of which search function we use it would be pretty easy to perform a simple delegation.

function genericSearch(searchFunction, album, store) {
   return serchFunction(album, store);
}

But this is pretty messy. We have to pass around references to the search function and then delegate the invocation to another method. It would almost be easier to just use binarySearch or linearSearch directly to find items in a collection. The thing is that this isn’t very semantic and doesn’t fit in with the language we want to use for the business.

// worst
binarySearch(albumMyCustomerWants, recordsAtUptownLocation);

// better, but still very bad
genericSearch(binarySearch, albumMyCustomerWants, recordsAtUptownLocation);

While this new solution programmatically fine it isn’t the best we can do. For example, why are we searching for a generic album across locations? It would be much cooler if we had a function that already knew what album we wanted. So lets do something like that.

First however, lets nail down our search algorithm. Lets pretend our search algorithm of choice for albums is the binarySearch and that is set via configuration on server startup. We don’t want to pass that algorithm around and reference our genericSearch all throughout the code.

// lets capture the search algorithm and return a function that holds onto it for us
function getAlbumSearcher (searchFunction) {
    return function (album, store) {
        searchFunction(album, store);
    }
}

This is simple delegation, but with a twist. Here we have used function currying to transform a 3-arity function into a 2-arity function. This means that the new function is proportionately simpler to use.

// After we have chosen our search strategy we get a function that allows us to search
var doWeHaveRecord = getAlbumSearcher(binarySearch);

// Later when we are searching for the albums we call that function
doWeHaveRecord(albumMyCustomerWants, recordsAtDowntownLocation);

See? Our code is already prettier. Unfortunately we still have the issue where any time we are searching for the record we need to pass around a reference to the record. The obvious problem with that is that someone might fat-finger the reference name and screw up our app, but another is that it might get overwritten. If this were a web-app then the identity of the record we are looking for would last for the entire lifetime of the request. So why don’t we encapsulate our reference to the record to avoid these problems?

function getAlbumSearcher(searchFunction) {
    return function (album) {
               return function (store) {
                          return searchFunction(album, store);
}}}

// At the beginning of the application lifecycle create our factory function
var recordSearchFactory = getAlbumSearcher(searchFunction);

// At the beginning of the search request create our search function
var doWeHaveRecordAt = recordSearchFactory(recordCustomerWants);

// Searching through each location
doWeHaveRecordAt(downtownLocation);
doWeHaveRecordAt(eastsideLocation);
...

Here’s where the really cool stuff happens. By using function currying we’ve transformed a 3-arity function into a 1-arity function and each step of the transformation was very simple. We’ve also given ourselves a much broader vocabulary to use in our programming. We could very easily take this code and modify it to search per store for something like:

// searching for the record at my fav location
doesLocalStoreHave(albumForMe);

The getAlbumSearcher code above might be a little confusing. That’s because it is a little bit complicated. We could have written it as a single function that would have read like this:

function searchFactoryFactory(searchFunction, album) {
    return function (store) {
        return searchFunction(album, store);
}}

This second definition is more legible, however we must pass the searchFunction and the record name at the same time. Obviously those two decisions aren’t inherently coupled and could be made at different times or different places in the application. It’s also not technically function currying.

I hope you can see how function currying is a good thing ™.