February 1, 2010

Bringing Unit Tests To Untestable Java Code

I deal with a lot of code that has never had any unit tests for it at all. In fact, it was often written in such a way that creating unit tests for it seems pretty horrific because you would find yourself having to load data into multiple database tables, set up all manner of services and files, etc. just in order to test it properly. So what I’m going to tell you is the simple, not-too-painful way I chose to make some of this code testable.

To me it’s all about removing all of the external dependencies from the code. If I can pull out all of the sections that are getting remote connections to EJBs, all of the data source lookups and queries, file reads, etc. and abstracting those out then I can test the code fairly easily because all I’ll be testing is the logic it had that surrounded all of those external calls to get data of one sort or another. So that’s what I do, I remove all of the code that does those lookups and abstract it out.

Note: Some of the feedback I’ve gotten tells me that I should make it clear that what I’m talking about below is only the refactoring part of getting your code to a unit testable state. After you perform some of the steps you might be well placed to look into either Spring or JSR-299 (for example Weld, which is their reference implementation) to do dependency injection. Or even into mock frameworks to do simpler implementations of your FooHelper for testing purposes. If you’ve got one you like a lot, let me know about it. I haven’t used any mock libraries for Java yet.

Step 1 - Use the refactoring capabilities in your IDE to extract some methods

I’m using Eclipse in this example, but I’m sure you could do much the same thing in Netbeans or any other major IDE.

Eclipse has a function on the context sensitive menu to extract a method. Just select a section of the code that goes and looks up something in a file or gets a JDBC connection and executes a query (or calls some code that does) and click the right mouse button to get the context menu, then select Refactor > Extract Method… and fill out the info in the dialog box where it asks you what to call your new method, etc. The refactoring will create an all new function which takes a set of parameters passed in and replace the code in the original spot with a call to that function. Repeat as needed on the offending section of code until you don’t have any code within it that isn’t actual logic that calls these new methods that use external resources.

Step 2 – Pull the new methods out into an external class

I don’t doubt that I could probably get Eclipse to do all of this too but at the moment I perform the next step manually.

Let’s say that the code that I was pulling methods out of was called foo(). Then I would create a new class called ProductionFooHelper at this point. I would pull all of the methods I extracted out of the class foo() was part of and put them into ProductionFooHelper(). That immediately breaks the foo() code because it no longer knows where the functions it used to call are anymore; but it leaves us with a version of foo that doesn’t require any exterior resources. That brings us to…

Step 3 – Extract an interface from the ProductionFooHelper class

Here Eclipse will do the tedious work for us again. Go to the ProductionFooHelper class and right click. Select Refactor > Extract Interface… from the context menu that pops up.

You can just select all of the methods to be in the interface and give it a name like FooHelper. Click OK and it will be created. Note that ProductionFooHelper should be marked as implementing the FooHelper interface.

Step 4 – Fix the failing calls within foo()

Go back to the class containing the foo() code and add a new parameter to it. The new parameter would be something like “FooHelper helper”. Then all the function calls within foo() that are currently showing as errors within the IDE can have “helper.” put in front of them. That will indicate that we’re calling that function on the passed in class. At this point everything in the code should resolve again except for the spot you originally called foo(). It will need to have an instance of ProductionFooHelper created and passed into it before it compiles successfully.

At this point we’ve extracted all the code which had external dependencies into another helper class and we have a production version of that class that should give us the exact same behavior we’ve always had. But if we were to produce a MockFooHelper that implemented FooHelper and produced faked results for unit tests, then we could test foo() at our hearts content knowing that we never have to do database setup or anything else unless we want to. The specific implementation of the functions in the FooHelper is up to us for testing purposes.

This may seem a convoluted way to get to testable code and maybe you’ve got much better ways to achieve this same thing. If you do, I’d love to know about it so I can improve my own coding skills. But if not, I have to say that it actually works. I’ve used it recently in a hierarchical fashion where innermost code had a helper interface extracted, then another close to it, and then yet a third. Then I wanted code that called all of them to be unit testable so I extracted a new interface that implemented the other three interfaces and added all new functions as well. The production helper had all of the methods for the innermost stuff as well as the outermost. The result is that I now have four different test points in the code where I can control everything that goes in and out and I was able to whip off a dozen new tests for code that once had none due to its complexity and the difficulty of setting something up.

January 21, 2010

100+ Year Old Color Photos and Amazon Kindle Apps Coming

The 1906 San Francisco Earthquake Aftermath, In Color – A couple of photos taken with an early color photo process have been reassembled (using Photoshop of course) so you can see that the past wasn’t really in black and white.

Amazon Adds Apps to the Kindle – I like my Kindle DX, I like it a lot, but I do not love it. I love my iPod Touch. It is my constant companion and many are the days when I return it home with a battery that is quite drained from use. I can think of many many ways to make my Kindle much better than it is today because the UI often very poor, even for it’s intended use as a book reader. Perhaps this will help it get past some of those problems or maybe it’s just too little too late.

Follow up to the post: Here’s the link to sign up for notification when the Kindle dev kit is released.

January 11, 2010

Turn Your iPhone/iPod Touch Into A WWII Fighter

I’ve always thought the apps that turn your iPhone/iPod Touch into a lighter, shotgun, lightsaber, etc. were pretty silly and this one is sillier than all of them. Nevertheless, I have to say it is probably the best one ever. I might even buy it myself.

January 8, 2010

The Best Comic Readers For OS X and Windows

Since some of my most popular blog entries ever were on the topic of comic readers for digital comics stored in .CBZ and .CBR files, I thought I would return to the topic for an update. It has been a really long time since I wrote about it and with one exception I wouldn’t use what I talked about then, it has been completely replaced with much better programs for both Windows and the Mac.

Mac OS X

Simple Comic – This is my current go-to reader. It’s simple, it works, and I like the loupe feature where you can zoom in on details if you need to.

ComicBookLover – This is a new reader that I only discovered when I decided I should compile a new list of recommendations. It seems to have more in common with ComicRack on Windows in that both are ready to keep track of your entire collection of comics as well as do the display of comics for reading.

Windows

ComicRack – I would argue that this is still probably the best choice for Windows users. I recommended it in 2006 and it is still being actively worked on today. Lots of features and a very dedicated developer have produced a really nice piece of work.

CDisplayEx – An open source version of one of the first comic readers I used on Windows. I would generally encourage ComicRack instead, but if you’ve got your heart set on open source, this one looks OK.

… and as a bonus…

Linux

Comix – Comical was never all that good and apparently stalled back in 2006 so it’s good to see that there is a reader out there for Linux that was updated in 2009 (early in the year admittedly but then digital comics aren’t exactly changing constantly). Comix looks like it’s probably a reasonably good choice and it’s open source so there’s at least a chance that it will get updates if it needs them.

January 5, 2010

5 Fun Board Games You Probably Haven’t Played

If you’re already someone playing the latest designer games from around the world or you live on BoardGameGeek.com, move right along there’s nothing to see here. But if you’re like so many people who think, “Let’s play a board game,” and then proceed to whip out Monopoly, Life, Candyland, Trivial Pursuit, etc. then let me bend your ear for a minute.

Board games have changed a lot in the last 15-20 years. Especially in the last decade or so as tons of cool new games have been released. Here are a few favorites of mine. Most of them are considered staples of the new generation.

Settlers Of Catan – The best known of the bunch with over 600,000 copies sold in the United States according to this recent Wired magazine article. This one pretty much defines how you can still have a competitive game yet not have it be the kind of zero-sum relationship destroyer that Monopoly is. With Monopoly I can’t win unless I first make you lose. With Catan, I can’t win without trading with you (especially in the early game), and we both gain points from stuff we do, but I don’t win by taking points away from you, I win by just being the first one to ten points. You might have scored nine points yourself and the fact that you did can cushion losing and give you encouragement to try again.

For me the only downside to this game is that it doesn’t play well with less than three people and the playtime is the longest of all the games listed here (it can easily be a couple of hours).

Animal Upon Animal – First of all, Candyland and Chutes and Ladders have a place. They are teaching games for colors and counting for little kids. However, once you know your colors and numbers to 100, you are past both of those games and you never ever need to come back to them. If you’re looking for a fun game for a little kid that can also be enjoyed by adults, look no further than Animal Upon Animal. It’s a dexterity game where you stack oddly shaped wooden animals on top of other wooden animals in a big pyramid. First player to get rid of all seven of his/her animals wins.

Little hands are sometimes a bonus rather than a hindrance and even if you knock over the entire pile adding a piece, you only take two pieces back into your collection. The rest go into the box. That keeps it from getting too frustrating for little kids. If you need to further even the odds it’s easy to have a player start with six pieces or five instead of the normal seven so they can more easily win.

Ticket To Ride – There are multiple versions of this train game with maps for different countries and even some slightly different rules. I’m used to the Ticket To Ride Europe version with it’s train stations (an additional piece that I don’t believe was in the original Ticket to Ride). It’s fun, it can be played in an hour or so (maybe 90 minutes at the longest) and it’s a simple game to teach to new players because you only have four things you can do in a turn and most of the time you’re going to only be choosing between two things to do.

Gather up the colored cards you need to claim routes between major cities (using super nifty plastic trains to mark your route) and try to keep the secret the longer routes you are trying to complete to score extra points.

Dominion – An awesomely great card game in a big box. Seemingly endless variety thanks to the fact that in any given game you’re picking a set of ten cards to use out of 25 available cards and different choices can completely change the feel of the game. Easy to teach, reasonably short playtime (often less than an hour), and expansions like Dominion Seaside can give you more variation than you can even imagine.

Carcassonne – You’ll notice a theme to the entries in this list. They’re very easy to explain to new players and they tend to have pretty short playtimes. This one is no exception. The mechanic is a simple one. Draw a tile from a set of tiles and see how you can place it by matching its edges to tiles already played. That part of it only takes a second. Then you decide whether or not you want to put one of your small stock of pieces (seven little wooden people) on the board in order to try to score some points.

There are probably a dozen expansions for this game if you find you like it (as I do) so you can really expand the array of tiles, pieces for scoring, and methods for scoring points to increase the strategy or complexity of the game.

I was lucky enough to get to play all of these except Carcassonne with family over the holidays and everybody had a great time. I finally went to bed at 3am but people kept playing for hours more after that!

January 4, 2010

Professor Layton And The Completed Game

As I’ve said before, the best feature of the Nintendo DS Lite is its adult-with-other-responsibilities friendly ability to pause a game at any point. But having a feature like that is only good if there are good games and I would call Professor Layton and the Curious Village one of those.

I really wasn’t sure if I would enjoy a game that was based upon completing puzzles, but by the time I finished it I had played for about 12 hours and completed approximately 100 out of the 120 or so puzzles that are available in the game and had definitely enjoyed it. It doesn’t seem like a tedious slog of solving one puzzle after another because it’s wrapped up in an adventure game where you travel from place to place, talk to other characters, search for hint coins, watch videos, etc. In other words there’s lots of meta-game on top of the puzzles so they don’t comprise the whole experience.

I didn’t end up going back to try and track down the last few puzzles I had missed once I finished the game. I definitely felt like it ended at the right time, because I didn’t end up burned out or wanting lots more. If you can, give this game a try and see if it’s for you.

December 31, 2009

Why Can’t Java Do Convention Over Configuration?

I was just reading an overview of Java EE 6 and I was struck by their handling of the web.xml file. In this article it is trumpeted as a great new feature, the monolithic web.xml file can now be chopped up into a set of files so you can group setup and configuration. And god knows, if there’s something you get a lot of in Java, it’s configuration.

Anyway, the heart of this is good, it’s in a good place. There’s no longer one big file, we can have several files and each one has its own purpose. You might even get a web.xml file that comes with some third party framework you’re using like Struts. However, then it starts to go off the rails (no pun intended):

However, because Servlet 3.0 enables you to modularize your deployment descriptors, the order in which these descriptors are processed can be important. For example, the order in which the descriptors for an application are processed affects the order in which servlets, listeners, and filters are invoked. With Servlet 3.0, you can specify the order in which deployment descriptors are processed.

Servlet 3.0 supports absolute ordering and relative ordering of deployment descriptors. Your specify absolute ordering using the <absolute-ordering> element in the web.xml file. You specify relative ordering with an <ordering> element in the web-fragment.xml file.

Uh huh. When Rails (as in Ruby on Rails) needed to order a bunch of stuff like migrations, they made a simple convention (for example, 001_filename.rb, 002_filename.rb, 003_filename.rb). When that convention didn’t work out for large groups of developers they changed and went with the date and time instead (as in, 0080402122512_one.rb). Rails pretty much always picks a convention whenever possible and then if they need to they come up with a way to override it.

There’s nothing wrong with having <ordering> and <absolute-ordering> elements at all. Give the developer an override, fine, but give them an easy way to just name their stuff and order it automatically without that. What the heck is wrong with files named 001_web.xml and 200_web.xml? Seriously? Why can there never ever be a convention that the software reacts to and uses so you don’t have to hack up some configuration file 100% of the time?

Subscribe

Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by
Movable Type 3.33