Tuesday, April 30, 2013

A Dynamic Factory

During my last iteration, one of my stories was to implement a way to start a new game for my iOS/Java/Ruby hodgepodge of a Tic Tac Toe game. This meant that I would need to have my server respond to multiple commands.

At that point, the only command it responded to was to make a move. I would post a request with the body equal to something like "square=1" and it would make a move in square 1. I didn't think it would be much work to allow it to respond to another command, but I quickly noticed a problem. If I added an if statement to check the command I was sending, what would happen when I needed to add yet another command? This looked like a clear open/closed violation.

I struggled to find a solution. After a couple missteps, I almost decided to put off fixing the issue and just implement the if statement, delaying the decision. Thankfully I decided to talk to my mentor, who suggested using a factory. I was familiar this pattern, having used it in the past. This is what my factory looked like.

require "newgame_handler"
require "square_handler"

class RequestHandler
  def self.create(request)
    name = find_key(request)

    if name == "newgame"
      NewgameHandler.new
    else
      SquareHandler.new
    end
  end

  ...
end

For every command I needed, I could just create a new class. My factory did make it easier to add new commands to my server, but it still felt wrong. This solution didn't really conform to the open/closed principle. Whenever I needed to add a new command, I would need yet another if statement. I really wasn't thrilled at that prospect. When I brought this up with my mentor, he showed me a Ruby function called Module.const_get.

Module.const_get allows you to pull in a constant that is loaded and floating around while your Ruby program is running by specifying its name. What made this so useful in my situation is that classes are constants. So now, using this function, I could grab a reference to my NewgameHandler by passing const_get the string "NewgameHandler." This gave me a way out of wrestling with my potential if/else chain.

require "newgame_handler"
require "square_handler"

class RequestHandler
  def self.create(request)
    name = find_key(request)
    Module.const_get(format_name(name)).new
  end

  ...
end

Here is my class after another iteration. As it stands, it makes use of Ruby's Module.const_get method and is now a dynamic factory. It instantiates classes on the fly, based on the command sent, and uses those created handlers to process the game. I'm starting to sense a pattern though. Maybe you can see it too. I still haven't gotten away from explicitly modifying the class for every new command. The new wrinkle, that I didn't notice before, is that I still have to require the file that the class lives in.

After slightly more searching, I ended up with current solution. I was able to remove the explicit requires by requiring the files based on the command name.

require "nil_handler"

class RequestHandler
  def self.create(request)
    name = find_key(request)
    begin
      require "#{name}_handler"
      Module.const_get(format_name(name)).new
    rescue NameError, LoadError
      NilHandler.new
    end
  end

  def self.find_key(request)
    request["Body"].keys.first
  rescue
    ""
  end

  def self.format_name(name)
    name.length > 0 ? "#{name.capitalize}Handler" : ""
  end
end

This solution does have its drawbacks. What if I can't load the right file or try to get a constant that doesn't exist? That's why I added in a NilHandler that does nothing with the request. That way my server keeps chugging along when there's a load error or a name error. There are still some potential security concerns because this handler could instantiate a class that I wasn't ready for. The worst I can see happening though is my server crashing because the returned class doesn't respond to the same interface as the other handlers.

It's possible that this solution was a bit of overkill for two commands or that it was premature. While, I'm not entirely sure about either of those, I did think it was pretty cool.

Thursday, April 11, 2013

An Update (Because It's Probably Due)

It's been a rough week. I've learned a lot, but that doesn't diminish the frustration. Looking back, there are probably some shorter paths I could have taken, but that's easy to say now.

My first task was to get my iOS app set up for continuous building on Travis. Thankfully they recently added support for objective-c. The setup is really simple. You add a single line to the config specifying your language is objective-c. That went pretty quickly, as you would suspect. The next part didn't.

My first build gave me certificate errors when Travis tried to run xcodebuild. "That's weird," I said to myself. I was surprised because running my build locally was pretty smooth. So I tweaked something, committed, and error. Tweak, commit, error. Towards the end of the day, I found my issue.

It turns out that xcodebuild will use the specified version of the sdk you want and will try and build it for the device, which of course needs to be signed. The way around this is to specify iphonesimulator, and a version if you want, with the -sdk flag. I submitted an issue to Travis and in the meantime copied their script and modified it by hand.

That wasn't the only issue I had with Travis. My next issue was a linking error where it couldn't find libOCDSpec2.a and thus couldn't build my application. I should have gotten to the fix earlier. Thirty-five builds later, I had a working solution.

For some reason, xcodebuild was not finding and building the OCDSpec2 project, so that lib file wasn't being generated. I still don't know why, but there's a fix. I compiled the project manually and copied that file into my project and linked against that one. Problem solved, but if OCDSpec2 updates I'll have to repeat the process.

My second task was to add Fitnesse testing into my project. Thankfully Eric Meyer had templates for XCode made for this. I missed a crucial step when I cloned his project though. I forgot to clone the submodule. This lead to about an hour or two of trial and error before I realized something. The files that the template copied into my project were blank. Something was wrong. Thankfully adding the submodules fixed the issue pretty quickly.

I was able to complete all three stories for my ipm on Wednesday. Thankfully the spike of Franklin (my http server) and Tic-Tac-Toe played on an iOS app took less time than expected. During the meeting, I got my next batch of stories. End-to-end player vs player and a gameover message.

The player vs player story is what I'm struggling with right now. It feels gigantic. I have to wire up Franklin, TTT, and iOS with unit tests and Fitnesse tests. It sounds like a lot, at least to me, considering I'm relatively new to iOS. Today was spent trying to get the interface setup with a view and then I worked on how the iOS app would talk to the server. I made some progress there and hopefully once that's done it'll start falling into place.

If this post sounds a little upset, it's probably because it's been a frustrating week. For a majority of it, I fell like I've been fighting software instead of writing code. That started to change this afternoon though. Hopefully now that I've gotten all this out, I can continue making progress tomorrow. If nothing else, I'm going to try and be better about my estimates.

Thursday, April 4, 2013

Piecing It Together

Yesterday I was given my next assignment. I knew it was coming, but it still sounds like a lot. The goal is to hook my Tic-Tac-Toe game up to my new web server. Then I need to create an iOS client that can play a game over a network, and eventually the internet. There's a bit more that goes into it too. I need to do things like setting up a continuous build and passing FitNesse tests as well.

This week is mostly practice though. I have to see how much work I think it will take to get each of the pieces working together. I also need to take care of the continuous build and a few other setup odds and ends. Then the whole project can start being broken down into stories. This is going to be an interesting change because now there will be hard deadlines. There's a lot to learn to make this work, but it does sound interesting. And hey, I should have something I can run on my phone by the end of this.

I want to try and write some more specific posts about what I'm doing to make all of this work but I've first got to make it work.