Thursday, May 9, 2013

The State Pattern

During my apprenticeship, I've encountered ideas I learned about in college. When I say this, I do not mean to imply that I learned everything I could about each topic. In fact, my apprenticeship has taken those foundations and replaced what I knew with a much better understanding. One example of this is a state machine.

A state machine describes how something behaves given a current state and transitions to the next state. It doesn't have to be software either. You can make a state machine diagram for traffic lights, for example. The key properties are that a state machine can only be in one state at a time, there are a certain number of possible states, and there are transitions from one state to another. One area of programming that makes extensive use of state machines is game programming.

In college, I was taught to implement state machines in a simple way. It boils down to a rather large class with a function for each action the state machine can take, a variable containing the current state, and a large switch statement. In all likelihood, I've written something like the following before.

While this state machine doesn't really do anything, it works. There's a bigger issue than it not doing anything though. It's possible that there are additional things wrong with it but that case statement in take_action causes me pain and is a glaring example of an OCP violation. I'm not pleased by having to check the state every time that I want something to happen. Before this apprenticeship, I would have accepted this as the cost of writing a program.

I now know that an answer to my issue is the state pattern. This pattern encapsulates each game state in an object. Each of these state objects conform to the same interface and correspond to single game state. In this way, my state machine no longer cares about checking the current state when it takes each action because the state variable is an object. That object already knows what to do in the current situation. This allows me to alter my current program to look more like the following.

Using the state pattern, I was able to move the take_action method out into each of the state classes and eliminate it from the state machine. My state machine should still behave the same way, but it favors creating more classes to additional whens in a case statement. Now, as long as the transitions between states are correct, I can call take_action within my run method and let each state class do what it's supposed to.

While I find this to be a very interesting pattern, I'm more surprised by my reaction to it. Before this apprenticeship and exposure to the SOLID principles, I would have just accepted that my code became unmanageable  That doesn't mean that I would have been alright with it. Most likely I would have tried to fix it, given up in disgust, and told myself that it's because I don't know what I'm doing. I probably would have taken a break from programming and tried to forget it ever happened. Before, if I had read the state pattern, it would have looked like needless complexity. Instead, I see it now as a way to continue using state machines without violating SOLID principles and leading me to more maintainable code.

Things feel different now. I can recognise when I'm going down a bad path. I know that there are ways to avoid it. Unfortunately, I sometimes realize this halfway down the bad path. There's still a long way to go before I know everything I need to. While that's only a subset of all knowledge and given how long it's taken me to get where I am, it's doubtful I'll ever know everything I should. I'm okay with that though. It just means I need to keep in mind how much farther there is to go.

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.