I'm in the process of creating the code that handles the "real-time" communication between the server and the browser for my game, using Socket.IO.
The first draft was mostly just a proof of concept. It followed the same structure of the many Socket.IO tutorials on the web, where you use Express to serve a web page which includes the client code. The server event handlers were all in the same file as the Express code. Of course, this is fine for proof-of-concepts, and tutorials, but it gets a little messy when your code gets more involved. My first task was to pull the code that handled communication into a separate module.
But what to name it? I wanted the module to expose the communication in domain verbs to the server. I kept thinking "I know there's a pattern for this - but what is it?" The name escaped me so I headed to the Internets. Oh, right - a "proxy".
After a little bit, I came up with this.
.
You may not have noticed but when I set up my NodeJs development environment, I forgot something really important. I didn't include any testing libraries! To rectify this I installed Expresso, and started creating some tests for the ClientProxy module. Only then did I realize that I needed to refactor. One of the warning signs that your code is doing too much at once is that your tests are hard to write. In this case it's pretty obvious - I've got an event handler factory object buried in the middle of my proxy code. Ouch.
That's why I love automated testing - testing drives design.
While refactoring, I noticed that I'd made a copy-and-paste error in my original code. See it? In lines 40-48 in the gist above, I tell Socket.IO to listen for 8 events, but only the "login" event handler would be invoked, no matter what event was fired.
Here's the ClientProxy, with the EventHandlerFactory passed in as a dependency, and the two tests.
.
When I run Expresso, it looks like this.
$ expresso
100% 2 tests
$
Yay!