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.

Thursday, March 28, 2013

I is for...

I is for Interface Segregation Principle.

This principle states that nothing should be forced to depend on methods that it doesn't use.

To illustrate this suppose there were a humongous class that handled making sandwiches (humongous sandwiches?). Now, as everyone knows, there are many kinds of sandwiches. There are toasted ones, open-face ones, and even bread-less ones. And while I'm not here to judge each sandwich, the point is that there are many different sandwiches and they are not all made the same way. To have each sandwich hold a reference to how to make anything but itself is wasteful. The bread-less sandwiches, as the name implies, don't have bread, so why should they know how to toast a piece of it?

Instead, each sandwich should depend on a reference to a subset of the large sandwich making class. This means that changes to how toasted sandwiches are made doesn't affect the bread-less ones, unless they are somehow also being toasted. I don't know enough about the different kinds of sandwiches.

In my own code, the closest I can come to this is the responders in my http server. I know that I've used them before, but that's alright, I think. The responders implement a very small interface. In fact, there's only one method and it's called respond. That isn't the only method that each responder has though. Some of them require additional methods to process the request cleanly and avoid an overly large respond method.

If I had pushed those methods up into the responder interface, instead of keeping them in the responders that required them, I would have been in violation of this principle. The responders that didn't use those extra methods could have just returned null or done nothing, but that would have been an unexpected behavior for anything relying on my responder interface. I'm not sure what principles that violates, but it can't be a good thing to do.

Again, if you don't agree with my description of this principle, please let me know. Also, I'm hungry again.


D is for...

D is for Dependency Inversion Principle.

This principle states two things. The first is that "high-level modules should not depend on a low-level modules." Instead, "both should depend on abstractions." The second is that "abstractions should not depend on details." In fact, "details should depend upon abstractions." This is a principle that I thought I understood until I sat down to write this post. It seems I was getting it slightly confused with Dependency Injection.

The idea is that changes made to low-level modules should not ripple up and disturb the high-level modules resting on top of them. The high-level module should depend in an abstraction, like an interface, instead of on a specific implementation of a low-level module. There is no way to eliminate ripples of change, but they can be confined to a minimum number of modules.

I will again be referring to my http server in this example. I keep coming back to Java to explain these principles because they are much easier to see with explicit interfaces.

In my server, I have a router that holds all of the possible routes that a request can take. This lives inside of and was also initialized by my server class. In order to make my server more flexible, I passed the router (complete with routes) into the server when the server was created. This is where I confused inversion with injection. I had merely altered the order in which the server and router objects were created. For my server, as it stands, this is good enough.

In order to truly invert the dependency, I would need to define a router interface and use that in the server. The interface to the router would be a part of the server and changes to the router should not affect the interface. Doing this would allow my server to remain unchanged even if I substituted an entirely new router in. In fact, I may have to make this change in the future. I'll wait until a real need arises though.

I feel as though I may have still gotten this one wrong, so please correct me if I am mistaken.

Wednesday, March 27, 2013

L is for...

L is for Liskov Substitution Principle

This principle essentially states that for a class N and a subclass of N called O then O can be substituted for N without breaking the program. Following this principle can help a program respect the Open/Closed principle. For this post, I have two examples. One where I successfully followed this principle and another where I fell into a classic trap.

Let's start with success. This example is again my responders in my http server. All of the responders implement a responder interface. Because they all do this, they are each interchangeable with the responder interface. Java confirms this by letting me use the interface as a function argument and not exploding when I instead pass in a specific responder.

This does not mean that all I had to do to follow this principle was to implement an interface. I had sorta violated it during a small presentation I gave on code smells, though I didn't know it at the time. During that presentation, I said that a square and a rectangle shared enough class data to be derived from a common class. After all, a square is a rectangle, right?

Without knowing it, probably because I hadn't read PPP yet, I had fallen into a classic trap. Mathematically a square is a rectangle but not in terms of setting attributes on a class. A square really only has one attribute, so updating the width also updates the height. On a rectangle, those two attributes can be updated independently.

The problem comes when I want to pass a square into a function that takes a rectangle. What should I expect setting the height to do? If it were a rectangle, then setting the height would not change the width. For a square, changing one changes the other. The confusion here is evidence that the proposed relationship between a square and a rectangle violates the Liskov Substitution Principle. Let's hope I can avoid that mistake in the future.

O is for...

O is for Open/Closed Principle.

This principle states that classes, modules, functions, etc. should be "open for extension, but closed for modification." In order to add new functionality to the software, one should not have to change the existing code. One should only need to add the new code with the desired functionality.

One way this principle manifests is with interfaces. Defining an interface and using that, instead of the implementations directly, allows the code that uses the interface to remain unchanged when new implementations are added. This is much easier to visualize in Java, where interfaces are explicitly defined, than in Ruby.

An example of where I have used this principle in my code is in the responders in my Java http server. Credit must go to Rick for our talk that moved me in this direction. In my server, there is a responder interface that defines a single respond method, which all responders must implement. The respond method takes in a request and returns a response. Each responder processes the requests differently. This allows me to have a FileSystemResponder, a RedirectResponder, or any kind of responder I want.

Adding these new responders does not change my existing code. The code depends on the responder interface and, as long as that interface doesn't change, my code doesn't care what kind of new responder I add. Because of this, my server can be made to respond in a new way with relatively little work. If I didn't use the interface, then my server might be limited to responding in a single way or require code changes for every responder.

Following this principle has made my server much more flexible and easily extendable.