Friday, December 16, 2011

Clojure Mocks

A few weeks ago a I wrote an HTTP server using Java. While testing, I made heavy usage of Mock objects. I didn't use a mocking framework, just hand rolled mocks. The motivation for this can be seen here. Now that I'm finished with the server I have been working on a Clojure project. Having just written a Java server, I find myself wanting to use mocks to testing everything in Clojure. However, this can be difficult with Objects. Here is how I'm mocking using Clojure.

Dependency Injection


Dependency Injection can be used similarly to the way one would in Java. The only difference is that dependencies are now functions as opposed to objects.

Bindings


This is the method I have taken the most advantage of. You simply bind all functions that the function under test uses. Like so...

(def mock-called-count (atom 0)) (def mock-called-content (atom nil)) (defn mock [& args] (swap! mock-called-count #(inc %)) (reset! mock-called-content args)) (binding [interactor/create mock] (create @customer))
Here, the create function use the method create in the interactor namespace. So, with the binding in place, when the create function calls interactor/create, it will actually call the mock function. In this case, the mock function just stores the data given to it and increments a call count. However, the possibilities are endless.

So, with these two great methods of mocking in Clojure, who needs a mocking framework?

Wednesday, December 14, 2011

Iteration Planning

Today I went through my first iteration planning meeting with a client at 8th Light. My previous experience with iteration planning has only been with internal project managers presenting stories as opposed to customers presenting stories. This offered a different dynamic than my previous experience in that I was being presented stories directly from the customer as opposed to the PM who represents the customer. I really liked that there was virtually no distance between the us and the customers, which allowed us to clear confusing points very quickly. The customers were very easy to work with and were very receptive to our guidance and feedback. We were able to estimate stories and the clients prioritized the stories so that we will be able to produce working software by the end of the iteration. One could say that the planning meet went "by the books" as I have been learning in the Project Management Course. At the end of the meeting it was cool to see satisfaction and agreement between both parties. This project will be the first client work that I do for 8th Light. I'm really excited to start providing value to the business!

Monday, December 12, 2011

Implementing Java Interfaces in Clojure

I recently ran into some hiccups while trying to implement a Java interface in Clojure. While it the documentation my make it appear seamless, there are a few quirks. I'll explain the different ways I've found of implementing an interface and the hangups/quirks of each.

(Note: I'll be implementing an Interface called "RequestHandler", which is part of a namespace called "HttpServer")

:gen-class


The unfortunate truth about this method is that it requires AOT compilation. So, in order to get this example to compile, you must add :aot [implement-java-interface.first-request-handler] to your project.clj file. Here's what it looks like.

(ns implement-java-interface.first-request-handler (:gen-class :implements [HttpServer.RequestHandler])) (defn -canRespond [this request] true) (defn -getResponse [this request] nil) implement-java-interface.main=> (.canRespond (implement_java_interface.first_request_handler.) nil) true
Looks pretty simple right? The first thing to notice is that to instantiate the class I had to call implement_java_interface.first_request_handler instead of implement-java-interface.first-request-handler. Because of the way that Clojure resolves namespaces, any dashes in namespaces are converted to underscores for file names. Therefore, we generated a class with underscores. There are a few ways to fix this. First, we can use the :name parameter of :gen-class

(ns implement-java-interface.first-request-handler (:gen-class :name implement-java-interface.first-request-handler :implements [HttpServer.RequestHandler])) (defn -canRespond [this request] true) (defn -getResponse [this request] nil) implement-java-interface.main=> (.canRespond (implement-java-interface.first-request-handler.) nil) true
Second, we can write a constructor method in the namespace,

(ns implement-java-interface.first-request-handler (:gen-class :implements [HttpServer.RequestHandler])) (defn -canRespond [this request] true) (defn -getResponse [this request] nil) (defn new-first-request-handler [] (implement_java_interface.first_request_handler.)) implement-java-interface.main=> (use 'implement-java-interface.first-request-handler) nil implement-java-interface.main=> (.canRespond (new-first-request-handler) nil) true
This is the preferred method. It allows us to use more Clojure-like constructs to create an object, i.e. calling a method within a namespace as opposed to calling a constructor on a class.

deftype/defrecord


Using deftype or defrecord is certainly a little cleaner than :gen-class and it doesn't require AOT compilation. Here's what it looks like.

(ns implement-java-interface) (deftype second-request-handler [] HttpServer.RequestHandler (canRespond [this request] true) (getResponse [this request] nil)) implement-java-interface.main=> (require 'implement-java-interface.second-request-handler) nil implement-java-interface.main=> (.canRespond (implement_java_interface.second-request-handler.) nil) true
Once again, our clean code is befuddled by the way Clojure resolves namespaces. Let's fix this by putting a method on the namespace.

(ns implement-java-interface.second-request-handler) (deftype second-request-handler [] HttpServer.RequestHandler (canRespond [this request] true) (getResponse [this request] nil)) (defn new-second-request-handler [] (second-request-handler.)) implement-java-interface.main=> (use 'implement-java-interface.second-request-handler) nil implement-java-interface.main=> (.canRespond (new-second-request-handler) nil) true
Excellent! We were able to use a method on the namespace to construct the class for us, just like the first example. Plus, this method doesn't require AOT!

reify/proxy


Last, but not least, let's use the reify feature of Clojure to implement an interface.

(ns implement-java-interface.third-request-handler) (defn new-third-request-handler [] (reify HttpServer.RequestHandler (canRespond [this request] true) (getResponse [this request] nil))) implement-java-interface.main=> (use 'implement-java-interface.third-request-handler) nil implement-java-interface.main=> (.canRespond (new-third-request-handler) nil) true
As you can see, reify is the cleanest of all the examples and works like we want it too right away.

Conclusion


Of the three, I would have to say that it's a close call between deftype and reify, but reify is my favorite. The two methods are very similar, however deftype is a little confusing with the namespace issues and constructing, but reify has the same benefit of not using AOT and is very succinct and clean as well. So, in the end, I will be using reify.

Wednesday, December 7, 2011

Http Server (2)

After finishing the my iteration of the Http Server, here's a few things a I learned:

I kind of like explicitly typed languages


I can't explain it, but I am somehow my comfortable programming in explicitly typed languages. There is something very comforting about knowing exactly what you are working with at all times.  I like not having to guess all the time. That's not to say that I don't like implicitly typed languages, but I don't have the same ease when working with them.

Not all IDE's are evil


During the first half of college I dabbled with using Eclipse and Xcode. I didn't like either. Then I switched to using TextMate. Then I switched to Vim. Then I switched back to TextMate. Then I became a .Net developer. So, naturally I started using Visual Studio. I never liked it. Visual Studio does way to much for you. Some developers like it, but, I think I'll pass on the 3-5 minute start up time. Right now, I'm at an awkward spot where I'm not in love with any editor or IDE. So, when I came to 8th Light and saw that lots of people were using IntelliJ, I wasn't too excited about it. However, at the strong encouragement of Micah, I decided to use it for my server. I must say, IntelliJ is a happy medium. I doesn't do too much for you, but it doesn't enough to save you a lot of hassle. This probably won't be the last time I use it.

Java Logging sucks


After messing around with the Java Logger forever, I decided to ditch it. It's just not worth it. Sure, it's nice if you need to write to the console and file with one interface, but it's not easy to use. In my opinion, it was poorly designed. Root loggers, parent loggers, default handlers and singletons are way to much complication for something that is just supposed to write informational messages for me. I'm considering writing my own Logger for Java. But, in the mean time, I'm just going to use print lines.

Thursday, December 1, 2011

Http Server (1)

As part of my apprenticeship, I have been working on building an Http Server this week. I'm writing the server in Java, which is a nice language to work with, albeit very verbose. Here's a few things I have learned while writing the server.

Factory Pattern and Dependency Injection


While writing my listener, I needed to instantiate a new handler upon receiving a request. Originally,  I would simply insatiate a new handler object and spawn it up in a new thread to handle the given request. This was working fine until my tests started to get too large. Anytime I tested the listener, I was essentially testing the entire system. While testing I had no control over what happened inside the listener. So, in order to make my tests more focused, I decided to implement a handler factory. Now, I simply pass in a factory to my listener and the listener calls the factory when it needs to instantiate a new handler. This is great because I can now pass in a mock factory that returns mock handlers. This allows me to test just the listener and not the handlers at the same time. Along the same reason as using the factory pattern, I have found the Dependency Injection has made my test 100% more testable.

Hand Rolled Mocks


As per the requirement of the task, I was not allowed to use any outside libraries other than JUnit and the Java Standard Library. Even so, I have found it very helpful to not have a mocking framework to mess around with. I've found that hand rolling mocks is significantly simpler than rolling mocks via a framework. While they may not be as powerful out of the box, they take a lot less time to set up and are easy to add whatever functionality you need. The only problem I have had with hand rolled mocks is keeping their function signatures in sync with their parent. However, I suppose if I had used the proper refactoring tools of IntelliJ it wouldn't have been a problem.

Hang Ups


My biggest hang ups so far have been Java related, Logging and Shutdown events. Logging in Java is uncharacteristically complex. You are unable to instantiate a logger and use it. Loggers are singletons, and they are assigned by name. So to get a logger you have to call the static method getLogger(String name) with the name of the Logger you would like to retrieve. In addition each logger can have multiple handlers, which allows writing logs to any number of places (console, file, memory, etc.). This is nice, but I was not aware that there is a default logger that writes to the console.  So when I attempted to add another handler that wrote the console, I was receiving lots of output. So, in the future, I will be sure to either disable the default handler or use it appropriately.

Shutdown events were another headache. In Java, you cannot simply intercept a SIGINT as with other languages. I needed to intercept the SIGINT in order to shutdown the server properly before exit. The only was to do this in Java is to add a Shutdown event handler. So, I added a handler and some logging statements within the shutdown handler to notify me if it was running. However, the shutdown handler was very sporadic, sometimes it would run and sometimes it would not. However, after a lot of debugging, I discover that the handler was being run every time but only the log messages where not being run every time. This is because every shutdown event handler runs concurrently. In another thread, the logger was being closed. So, sometimes I would log a message before it would close and sometimes it would close first. 


All in all, programming the server in Java has been fun, albeit a challenge at some points.