Sunday, February 21, 2010

How I learned to stop worrying and love Unit Testing

I admit it. Throughout my whole career at Microsoft, even as a Dev Lead, I was not a true believer in Unit Testing. That's not to say I didn't write unit tests or require my team to write tests. But I didn't believe that the benefits reaped from unit testing were sufficiently valuable given the time it took to write them (for me, about equal to the time to implement the product code itself).

Now, post-Microsoft, I am a true believer. A zealot even. I can't imagine a world in which I write code that has a ton of unit tests covering it.

So what changed? My eyes have been opened to a development world in which real testing infrastructure exists. In my former role, what I used was a testing framework known as Tux, which ships with Windows CE. It was enhanced for Windows Mobile and given a usable GUI. The result was something like JUnit, eg, a simple framework for defining test groups and specifying setup/teardown functions. The GUI was very much like the NUnit GUI.

So far, so good. There's nothing wrong with this setup. However, a test-running framework is necessary but not sufficient for unit testing. The missing piece was a mocking infrastructure.

One of the most frustrating things about working for Microsoft (and I'm sure the same is true of other big software firms) was that everything, and I do mean everything, had to be developed in-house. For legal reasons we couldn't even look at solutions available in the open source community. The predictable result is that a massive amount of effort is expended to duplicate functionality that already exists elsewhere. In many cases the reality of product schedules and resource constraints mean that we simply must do without certain functionality entirely. This was the case with mocking. Developers were left to create their own mocks manually, or figure out how to write a test without using mocks. I identified the lack of a mocking infrastructure as a major problem, but failed to do anything about it.

Exeunt Gabe stage-left from Microsoft to Kikini and a world of open source.

At Kikini we use JUnit for running tests and a simply beautiful component called Mockito for mocking. I cannot emphasize enough how wonderful Mockito is. Mockito uses Reflection to allow you to mock any class or interface with incredible simplicity:

MyClass myInstance = mock(MyClass.class);

Done. The mocked instance implements all public methods with smart return values, such as false for booleans, empty Collections for Collections, and null for Objects. Specifying a return value for a specific call is trivial:

when(myInstance.myMethod(eq("expected_parameter"))).thenReturn("mocked_result");

The semantics are so beautiful that I am certain that readers who have never heard of Mockito or perhaps have never even used a mocking infrastructure can understand what is happening here. When the method myMethod() is invoked on the mock, and the parameter is "expected_parameter", then the String "mocked_result" is returned. The only thing which may not be completely obvious is the eq(), which means that the parameter must .equals() the given value. The default rules still apply so that if a parameter other than "expected_parameter" is given, the default null is returned.

Verifying an interaction took place on a mock is just as trivial:

verify(myInstance).myMethod(eq("expected_parameter"));

If the method myMethod() was not invoked with "expected_parameter", an exception is thrown and the test fails. Otherwise, it continues.

Sharp-eyed readers will note that the functionality described so far requires that equals() be properly implemented, and when dealing with external classes this is sometimes not the case. What then? Let's suppose we have an external class UglyExternal, it has a method complexStuff(ComplexParameter param), and ComplexParameter does not implement equals(). Are we out of luck? Nope.

UglyExternal external = mock(UglyExternal.class);
MyClass myInstance = new MyClass(external);
myInstance.doStuff();
ArgumentCaptor<ComplexParameter> arg = ArgumentCaptor.forClass(ComplexParameter.class);
verify(external).complexStuff(arg.capture());
ComplexParameter actual = arg.getValue();
// perform validation on actual

This is really awesome. We're able to capture the arguments given to mocks and run whatever validation we like on the captured argument.

Now let's get even fancier. Let's say we have an external component that does work as a side-effect of a function call rather than a return value. A common example would be a callback. Let's say we're using an API like this:

public interface ItemListener {
    public void itemAvailable(String item);
}

public class ExternalClass {
    public void doStuff(ItemListener listener) {
        // do work and call listener.itemAvailable()
    }
}

Now in the course of doing its job, our class MyClass will provide itself as a callback to ExternalClass. How can we mock the interaction of ExternalClass with MyClass?

ExternalClass external = mock(ExternalClass.class);
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        ItemListener listener = (ItemListener)args[0];
        listener.itemAvailable("callbackResult1");
        return null;
    }
}).when(external).doStuff((ItemListener)isNotNull());

We use the concept of an Answer, which allows us to write code to mock the behavior of ExternalClass.doStuff(). In this case we've made it so that any time ExternalClass.doStuff() is called, it will invoke ItemListener.itemAvailable("callbackResult1").

There is even more functionality to Mockito, but in the course of writing hundreds of tests in the past 9 months I have never had to employ any more advanced functionality. I would say that only 1% of tests require the fancy Answer mechanism, about 5% require using argument capturing, and the remainder can be done with the simple when/verify functionality.

The truly wonderful thing, and the point of my writing this blog entry, is that a mocking infrastructure like Mockito enables me to write effective unit tests very quickly. I would say that I spend 25% or less of my development time writing tests. Yet with this small time investment I have a product code to test code ratio of 1.15, which means I write almost as much test code as product code.

Even more important, the product code I write is perforce highly componentized and heavily leverages dependency injection and inversion of control, principals which are well-known to improve flexibility and maintainability. With a powerful mocking infrastructure it becomes very easy and in fact natural to write small classes with a focused purpose, as their functionality can be easily mocked (and therefore ignored) when testing higher-level classes. I have always been told that writing for testability can make your product code better, but I never really understood that until I had the right testing infrastructure to take advantage of.

Now, I'm a believer.

Sunday, February 7, 2010

A Taxonomy of Software Developers

After spending years of my previous life at Microsoft as a Dev, Tech Lead, and Dev Lead, I've worked with a broad range of software developers from the US, China, India, and all over the world. I've also been involved in interviewing well over a hundred candidates, and many hiring (and some firing) decisions. From this I've come up a taxonomy describing the characteristics of the various software developers I've encountered, how to spot them, and what to do with them.

Typical Developers

The hallmark of a Typical Developer is a relatively narrow approach to problem solving. When fixing a bug, they concentrate on their immediate task with little regard to the larger project. When they declare the bug fixed, what that means is that the exact repro steps in the bug will no longer repro the issue. However, frequently in fixing the issue described in the bug, they have missed a larger root cause, or have broken something else in the system. This is illustrated in Fig. 1:


In most cases the code a Typical Developer writes is a very small net improvement for the overall project when viewed from a release management perspective. Sometimes the traction is zero if the issue that they created is just as severe as the issue they fixed. Sometimes the traction is slightly positive if the issue they created or the case they missed is easier to fix than the original issue.

When viewed from an engineering management perspective, however, the picture is very different. This is due to the nature of the approach Typical Developers take when actually writing code. A typical bug has the form "under condition X, the project behaves as Y, when it should behave as Z." The Typical Developer is very likely to fix the problem in this way:

// adding parameter isX to handle a special case
void doBehavior(boolean isX) {
  // usually we want to do Y, but in this special case we should do Z.
  if (isX == true) {
    doBehaviorZ();
  } else {
    doBehaviorY();
  }
}

The Typical Developer simply figures out how to directly apply logic to the code that determines behavior, then make the code behave differently based on that. This is reasonable, but if it's the only way the developer can think of to change behavior, after a while working in the same code it begins to look something like this:

void doBehavior(boolean alternate, String data, File output, Enum enum) {
  if (enum == STATE_A) {
    doBehaviorA(data, alternate);
  } else if (enum == STATE_B && !(alternate || data == null)) {
    doBehaviorB(output);
  } else {
    switch(enum) {
      case STATE_B:
      case STATE_D:
        doBehaviorA(data, !alternate);
        // FALLTHROUGH!
      case STATE_C:
        doBehaviorC(output);
        if (alternate) {
          doBehavior(!alternate, null, null, enum);
        }
        break;
      default:
        // We should never get here!
        assert(false);
        break;
    }
  }
}

When I see code after months of a Typical Developer working on it, this is my reaction:


The Typical Developer will never take a step back and think "Hmm, we're getting a lot of these kinds of issues. Maybe the structure of our code is wrong, and we should refactor it to accommodate all the known requirements and make it easier to changes."

Now the project is in trouble. The team may be able to release the current version (often there is no alternative) after exhaustive manual testing, but the team can never be confident that they fully tested all the scenarios. The first priority after releasing will be to remove all the code written by the Typical Developer and write it from scratch.

Another characteristic of Typical Developers is insufficient testing. Often the code they write will be difficult or impossible to unit test. If unit testing is a requirement, they'll write tests which are just as bad as their code. In other words the tests will be unreliable, require big changes to get passing when a small code change is made, and not test anything important. Furthermore the same narrow approach to development shows through in manual testing. The Typical Developer will follow the steps in the bug when testing their fix, and never stop to think "what other behavior could be impacted by my change?"

Typical Developers are quite willing to chalk up their constant regressions and low quality to factors like "I'm working in legacy code" or "I'm not familiar with this area" or "the tools aren't good enough." Though all of those things may be true, that is the nature of software development, and Typical Developers don't understand how to change their environment for the better.

The root cause behind these failings is most often that the Typical Developer is simply not cut out for real software development. Because the software industry is so deeply in need of talent, no matter how marginal, Typical Developers will always find work. Hiring managers are too willing to fill manpower gaps in order to ship on time. (In fairness, Microsoft managers are pretty good about avoiding this pitfall. However, there are times when it is considered OK to "take a bet" on a marginal candidate.)

A special type of Typical Developer is the brilliant person who simply doesn't care enough. They're in software development because it pays well and they can skate by with putting in 40hrs a week. These Typical Developers are especially annoying because they'll employ their brilliance only when justifying their lazy workarounds, and not on actual design and implementation.

What should managers do with Typical Developers? In most cases manage them out as quickly as they can. Though a Typical Developer may be of use in the final push of releasing a project, in the long run having them working on a project is a net negative. Even if Typical Developers came for free, I wouldn't hire them. It is exceedingly rare for a Typical Developer to become a Good Developer, though in rare circumstances I've seen it happen under the guidance of Great Managers.

Good Developers

Good Developers fix bugs and deliver features on time, tested, and adaptable to future requirements. This is illustrated in Fig. 2:


Once a Good Developer delivers a bugfix or feature, typically that's the last you hear of it. A Good Developer will not fall into the traps that a Typical Developer does. When they see a pattern emerging they identify it and take steps to solve the issue once and for all. They are not afraid of refactoring. They'll come into your office and say "Hey, it's not sustainable to do all these one-off fixes for this class of issue. I'm going to need a week to re-do the whole thing so we never have to worry about it again." And you say great, please do it!

Good Developers will encounter the same environmental issues Typical Developers do, eg, legacy code, or weak tools. Good Developers will not let this stand. They'll realize that if a tool is not good enough to do a job, then they have to improve the tool or build a new tool. Once they've done that, then they'll get back to work on the original problem.

Good Developers are Good Testers. Their code is written to be testable, and because they are able to take a larger view, they have a good idea of the impact of their changes and how they should be tested. Pride is also a factor here. Good Developers would be embarrassed and shamed if they delivered something that wasn't stable.

From a release management perspective, Good Developers are well liked, though their perceived throughput may not be high since they are spending time making the system as a whole better and not just fixing a bug as fast as they possibly can. Good managers recognize and nurture this. Bad managers push them to put in the quick fix and deal with the engineering consequences in-between releases. Good Developers will protest against this but often acquiesce. A Good Developer in the hands of a Good Manager can turn into a Great Developer.

Managers should work hard to keep Good Developers since they're so hard to find and hire. That does not mean forcing them to remain on the team, as doing so risks turning a Good Developer into the "brilliant" variety of Typical Developer described above. Reward Good Developers well and give them interesting things to work on.

Great Developers

Exceedingly rare, the hallmark of the Great Developer is the ability to solve problems you didn't know you had. This is illustrated in Fig. 3:



When tasked with work, a Great Developer will take a holistic view of their task and the project they're working on along with full cognizance of the priorities upper management has for this release and the next. A Great Developer will understand the impact of a feature while it's still in the spec-writing phase and point out factors the designers, PMs, and managers hadn't thought of.

When designing and implementing a feature, a Great Developer will take the time to design in solutions to problems that Good Developers and Typical Developers have run into, even though they're not obviously connected. A solution from a Great Developer will often change how a number of components work and interact, solving a whole swath of problems at a stroke.

Similar to Good Developers, a Great Developer will never let lack of tools support or unfamiliar code deter them. But they'll also re-engineer the tools and legacy environment to such a degree that they create something valuable not only to themselves but to many others as well.

Unlike Good Developers, a Great Developer can almost never be coerced into compromising long-term quality for expediency. They'll either tell you flat out "no, we need more time, period" or they'll grumble and come in on the weekend to implement the real fix themselves.

Sometimes mistaken for a Great Developer is the Good Developer in Disguise. These Good Developers have recognized the impact on others that a Great Developer has, and seek to emulate that by engaging almost exclusively in side projects related to tools improvement and "developer efficiency" initiatives. The Good Developer in Disguise has no actual time to do their own work, but fools management into believing that they're Great Developers. Truly Great Developers improve their environment as a mere side effect of them doing their own job the way they think it ought to be done.

It goes without saying that Great Developers should be even more jealously guarded than Good Developers, with the same caveat about not turning them into prisoners. The flip side is that Great Developers should not be allowed to go completely off on their own into the wilderness. No doubt they will build something amazing, but it runs the risk of being something amazing that you don't need. Better to give broad, high-level goals and let them do their thing.

Final Note

Although I named Typical Developers "typical," I mean that they're typical in terms of the overall industry. Although there were enough Typical Developers at Microsoft, most fell into the Good Developer category.

Friday, January 29, 2010

Poor Beanshell Performance and Custom Functions for JMeter

I'm building a relatively complex JMeter test plan to simulate load on the Kikini website. As soon as you need to do anything remotely complex, you exceed the capability of the built-in JMeter configuration elements and functions. The initial version of my test plan therefore used the BeanShell capability, which allowed me to do relatively complex things in a familiar language (BeanShell is essentially interpreted Java).

All fine and good until we need to run tests longer than 10 minutes or with more than 10 threads. An issue in BeanShell causes massive slowdowns if used inside loops (eg, inside a sampler), which in fact was what I was doing. When I worked around the issue by resetting the interpreter on each call, I found that JMeter was spending so much time processing BeanShell code that it couldn't effectively scale up to more than about 10 threads. The bottom line is that BeanShell is unfit for use if it must be called repeatedly in a JMeter test.

The only way I could find to get the complex behavior I want without compromising performance was to implement my own JMeter function. JMeter offers a number of simple functions out-of-the-box. Although JMeter isn't really an API, it does have a Function interface which you could implement. Then from inside any test element, you can call your function:

${__myFunction(arg1, arg2)}

And you'll get back a string that is the result of your function. Before we get to function class itself, there is some background to discuss.

First, JMeter isn't an API. But with a little bit of work, you can program against it. If you download the JMeter binary distribution, you can extract ApacheJMeter_core.jar. This JAR contains the interfaces you'll code against.

Second, you need a way to get your custom function onto JMeter's classpath. You can set the search_paths system property, and JMeter will find it. This is great because then you do not have to modify the JMeter distribution to use your custom functions.

Once you're ready with your custom JAR, you can invoke JMeter:

jmeter -Jsearch_paths=/path/to/yourfunction.jar

Alright, on to the code. This is a skeleton (please ignore the naming) which will simply return Array.toString() on the arguments you give:

package com.kikini.perf.jmeter.functions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

public class MaskUserIDFunction extends AbstractFunction {

    private static final List<String> DESC = Arrays.asList("uid_to_mask");
    private static final String KEY = "__maskUserID";

    private List<CompoundVariable> parameters = Collections.emptyList();

    @Override
    public String execute(SampleResult arg0, Sampler arg1) throws InvalidVariableException {
        List<String> resolvedArgs = new ArrayList<String>(parameters.size());
        for (CompoundVariable parameter : parameters) {
            resolvedArgs.add(parameter.execute());
        }
        // TODO: mask the user ID in resolvedArgs.get(0). For demo purposes,
        // just return the arguments given.
        return resolvedArgs.toString();
    }

    @Override
    public String getReferenceKey() {
        return KEY;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void setParameters(Collection arg0) throws InvalidVariableException {
        parameters = new ArrayList<CompoundVariable>(arg0);
    }

    @Override
    public List<String> getArgumentDesc() {
        return DESC;
    }

}

There are a few crucial things to note here. The package name contains ".functions". That is a requirement, otherwise your function will not be recognized by JMeter. Notice that the type of the arguments is CompoundVariable. You must call execute() on them to resolve them to a String.

Otherwise this is relatively straightforward. Now I can call my function from inside a sampler:



And it will return the correct results:


So, how do Java functions perform versus the BeanShell functions? My test plan had about 10 samplers, most of which used BeanShell before, but now use native Java functions. My dedicated JMeter machine is a dual-core system with 2GB of RAM.

Before: JMeter maxed out at ~45 requests per second, 90%+ CPU usage
After: Generates 150+ requests per second with 2-3% CPU usage

Huge win! I don't actually know what the limit is now but I'm guessing I could get thousands of requests per second now.

Sunday, January 24, 2010

Releasing simpledb-appender as open source

I've released the SimpleDB appender I wrote as open source under the Apache 2.0 License. The project is hosted here:

http://code.google.com/p/simpledb-appender/

The purpose of this project is to allow Java applications using the SLF4J API with Logback to write logs to Amazon SimpleDB. This allows centralization of the logs, and opens powerful querying capabilities. Also scripts and tools are included so that even non-Java applications can have their stdout/stderr logged to SimpleDB as well.

The project is tested and works well. Developers familiar with SLF4J should have no problem integrating it into their apps. The documentation for using it as a tool for non-Java applications is a little weak but I have a demo shell script that should at least get folks started.

Let me know how it works for you!

Thursday, January 14, 2010

Amazon Web Services Expanding into Asia

Last year, I privately speculated that having launched datacenters in the Eastern US and Western Europe, the next obvious locations for Amazon Web Services (AWS) would be the Western US and Asia. In December 2009, AWS announced availability zones in Northern California.

What I didn't realize until today was the AWS actually announced their intentions to expand into Asia back in November 2009. Multiple availability zones will be available in Singapore in the first half of 2010.



Singapore does make some sense as a location. A glance at the map (source: openstreetmap.org) reveals that Singapore is pretty central, located roughly equidistant from China, India, and Australia. So if AWS is persuing a strategy to minimize the average global latency, it is probably a good choice. It also offers a relatively stable political and economic environment, though there is some political risk to locating yourself in an authoritarian country.


But when I first thought about a datacenter in Asia, my thought would have been hosting it in Korea. Korea is one of the most connected (in the data networking sense) countries on Earth, and is in close proximity to the other two most important markets in Asia: China and Japan. Korea is a very stable political and economic environment, and doesn't have the significant political risk associated with hosting in China or the less significant risk of Singapore. Latency from Korea to China and Japan is very low. I imagine the cost of running a datacenter in Korea is not much more expensive than Singapore, given that living standards are comparable.

Still, I can't complain. Hosting in Singapore will allow a better web experience for users throughout Asia. I hope to see AWS continue expanding geographically.

Friday, December 25, 2009

My Favorite Innovations of 2009

One of the great things about our culture is constant innovation. I can honestly say that new products and services have made my life better in some way in 2009, and I'd like to call those out as a way of congratulating the people and companies who created them. None of the following actually came about in 2009, but 2009 was the year that I started to use them.

Amazon Kindle

The first time I saw a Kindle was in the Microsoft 117 Cafe, when Jerry Lin joined us for lunch and shared the latest gadget he'd received from Amazon. Jerry is known to be a prolific Amazon customer, notorious for receiving daily deliveries to his office (actually, he was rarely at work before the typical 11am-2pm delivery time, relying on the patience of neighboring officemates to sign for his packages). So it was no surprise to learn that his latest toy was a Kindle (version 1), which he demoed for us. The E Ink screen provides a reading experience much closer to paper than a computer display, making it less stressful on your eyes. But this atypical display, combined with the curious vertical silver reading position indicator and scrollwheel, make the device look like something envisioned in the 1960s: a bizarre amalgamation of analog and digital.

Nevertheless, the merits of the device were quite clear: newspapers, magazines, and books delivered wirelessly to a device with up to two weeks of battery life and a size and weight more compact than a single book. As a frequent (often international) traveler, I could immediately see the value of this. One of the less expected things about my time living in China was that I began to really miss the simple pleasure of reading. With something like the Kindle I could have an entire bookstore at my fingertips, anywhere in the world. Jerry did admit a downside: the available book selection, while large at hundreds of thousands, did not always contain the book you are looking for. But on the other hand the selection is large enough that you'll never run out of books you want to read. Jerry told us he had returned all the books he had bought from Amazon in recent years (which Amazon admirably allowed) and repurchased them on Kindle.

I promptly ordered a Kindle, which at the time (late 2008) was on "back order." In fact, it was no longer in production, and all pending orders were upgraded to the superior version 2. In Feb 2009 I finally received my Kindle 2.

The Kindle has changed my reading habits. The form factor makes the reading experience more pleasant, especially compared to reading large hardcover books. Wireless delivery of The Economist, which arrives Friday morning like clockwork, is a thousand times more reliable than receiving the same in the mail. By mail The Economist would arrive sometimes Friday, often times Saturday, and disappointingly often on Monday, which would leave me without enough time to read a full issue before the next issue arrived. The availability of an iPhone client and the capability of the Kindle and the iPhone to sync last-read positions makes it possible to read on-the-go without missing a beat. The overall result is that with the Kindle, I find myself reading more.

I'd like to take a moment to emphasize this last point, and note that the same has been true every time a medium has evolved, despite criticism from those who oppose or fear change. When the phonographic record gave way to the CD, many viewed this as a step backward for recorded music. They moaned that the digital CD could never capture the nuances of an analog record, and the small packaging made album art less relevant. The truth is that the CD is capable of storing and playing back audio with a fidelity that comfortably exceeds the capability of most humans to perceive. The loss of a few square inches of medium for album art is regrettable, but it was never something that was important to the experience of music, much less central to it. But besides affording listeners a higher fidelity listening experience, the slimmer, smaller CD enabled listening to music not just in the home, but in the car and on the sidewalk and in the subway in a way that records or tapes never could. CD recorders enabled people to make flawless copies of their collections for their cars or public transit commutes. Listening to music was now a ubiquitous feature of life. I don't need to point out how this became even more true with the advent of MP3 encoding and devices like the iPod. It is far, far easier to count people not wearing earbuds on the subway or bus than counting those with. All this in the face of the exact same tired criticism from the same old critics.

As it was with music and CDs/MP3s, so it is and will be with books and eBooks. Yes, eBooks as they exist today have lower fidelity compared to paper. Devices like the Kindle 2 support only 16 shades of black and white, and dealing with images and photographs is clunky. If anyone doubts that these problems will be solved in the next couple years along with the inevitable march of technological progress, I'm prepared to back up my confident words with a wager. However, I doubt any readers would dare bet against this. And let's look at what even the primitive readers allow today: reading essentially your whole library at any time and place. No longer do I have to choose which single book to take with me on a trip, nor need I attempt to stuff a 600 page hardcover in my laptop bag to read on the bus. All the books I own and thousands that I don't are available to me in a convenient package. And even if I find myself waiting in a lobby for 20 minutes without my Kindle, I have my iPhone, were the book I'm reading is waiting for me, synced to the page I last read on my Kindle.

The Kindle represents more than just a cool device and a premium reading experience. I'm sorry if you like the smell of ink, or the texture of paper, or displaying your book collection on shelves as though they were trophies. The Kindle represents the beginning of a resurgence in reading, making books and newspapers and knowledge much easier for everyone to obtain. After all, that's what reading is about, right?

Zipcar

Zipcar offers members by-the-hour car rentals in urban areas. Scheduling is done online or via an iPhone app, and can be done mere minutes before you get the car. Members use a special magnetic card (or the iPhone app) to lock and unlock the car; keys and a gas card are inside. In most cases the cost is less than $10/hr, which gets you a standard compact like a Honda Civic, or a light utility vehicle like a Scion xB, and includes mileage, insurance ($500 deductible) and gas. In urban centers, garages containing zipcars are located every few blocks.

The result is that for people who live in urban areas that have fairly good public transportation and where car ownership is prohibitively expensive (parking in downtown San Francisco runs $500/month), Zipcar is an excellent option. It's perfect for me, since I visit San Francisco every few weeks.

Moreover, it changes the equation a bit for people who are deciding where to live. Although it is often more expensive to live in areas like downtown where good public transportation is available, if you can do away with the expense of owning a car, living closer downtown becomes more viable. This is a net positive since living closer to where you work, shop, and play puts less stress on both the environment and your pocketbook.

Netflix Watch Instantly Streaming

I've been a customer of Netflix since 2004. I've always thought their model for renting DVDs was almost perfect: huge selection, low hassle, very convenient, and affordable. In the past few years Netflix has been quietly transforming itself into a company that deals in streaming content as well as their traditional rent-by-mail service. It's heartening to see a company acknowledge the future and embrace change rather than fear and reject it.

The change I'm talking about is the diminishing importance of physical media for movies. Before Blu-ray even came out, pundits spoke of it as the last physical format for movies. For mass-market purposes, they are probably right. At normal viewing distances and screen sizes, 1080p Blu-ray discs are not too far off from the limit of human perception of detail in moving images. Certainly 1440p and higher will eventually come out, but the difference between that and what's currently available will be unnoticeable to most. In short, there is little compelling reason for another revolution in disc formats.

The advantages of delivering movies over the Internet are clear: cost, convenience, selection. The question is who's going to deliver the content, and how's it going to get onto the TV in my living room? Netflix wants to be the one to do that, and to some extent they already are.

Netflix's now has a substantial catalog of titles available for streaming. Customers paying as little as $8.99 a month can stream unlimited content. Though a lot of the available content is cruft, I have noticed that more and more I am able to find quality content. I've been watching Lost on Netflix streaming, available in HD to boot. There are tons of great movies available, from classics to new releases, though almost never any recent hits. But the quality and quantity has been moving relentlessly upward.

So, how does it end up on my TV? Because if it's just on my 13" laptop screen, that will never replace DVD, let alone Blu-ray. For my roommate Eddy's birthday, he received a Blu-ray player, with built-in Netflix streaming capability, which is not uncommon among Blu-ray players (as well as a capability of the XBox360 and PS3, already in millions of living rooms). The device has WiFi, and can connect via my Netflix account to my "watch instantly" queue. In the several months that we've had the player, we've haven't played a single Blu-ray disc, but we've watched at least a hundred hours of streaming Netflix.

I look forward to Netflix making more deals and expanding their TV and movie selection, as well as offering more titles in HD. Wave of the future, dude, 100% electronic.

Honorable Mention: Virgin America

It doesn't necessarily fit into the category of "innovative," but certainly VA has changed things for the better. With its fleet of new A319/A320 planes, with live TV and on-demand music, TV, and movies, flying VA is very comfortable. The in-flight entertainment system even allows ordering food and drinks. Additionally, WiFi is available in-flight for about $10.

All this is nice, but it should be standard for new aircraft. The primary way VA has made things better is by giving other carriers some real competition. Previously, the best deals flying SEA/SFO were typically with Alaska, with its not-so-new fleet of 737s. A typical roundtrip ran $250-$300. VA flights can be found for as little as $39 one way (plus tax). A typical SEA/SFO roundtrip costs $110 with tax. This low-cost, comfortable and convenient flight has allowed me and my girlfriend to see each other quite often.

Gotta love a competitive market!

Sunday, December 20, 2009

Loose Dependency Injection

In the past year or so I've come to see the immense value in the principal of Inversion of Control (IoC)/Dependency Injection (DI) (see Fowler), and frameworks like Spring. Besides keeping classes and components isolated and focused in purpose, it also makes testing easier because instead of injecting real implementations, you can inject mocks into the component under test.

However, like any good idea, if taken to the extreme it becomes counterproductive. If everything a moderately complex class did was abstracted and injected, you would end up with a confusing and incoherent jumble of tiny classes. You would also risk exposing too much of the internals of a class by requiring any consumer of that class to create and inject pieces unrelated to the behavior the consumer wishes to dictate.

Let's make a simple example. Suppose we had a component that resizes an image. But in order to complete its work, needs to create a temporary file. Let's first take a look at an implementation that doesn't use DI.

public class ImageResizer {

    public File resizeImage(File image) throws IOException {
        File tmp = File.createTempFile("tmp", null);
        
        // do work on tmp ...
    }
}

Simple enough, but how are we going to test this? It uses a static method, which we don't own and can't change, to create the temporary file. We don't have any way to mock it or inspect it, so we're pretty much out of luck for testing it.

Now let's use a strict form of DI. We'll abstract the temporary file creation into a separate class, and require consumers to provide an implementation at construction time.

public class ImageResizer {

    /** Abstraction of temp file management */
    public static class TempFileFactory {
        File createTempFile() throws IOException {
            return File.createTempFile("tmp", null);
        }
    }
    
    private final TempFileFactory fileFactory;
    
    /** Dependency-injection constructor */
    public ImageResizer(TempFileFactory fileFactory) {
        this.fileFactory = fileFactory;
    }
    
    public File resizeImage(File image) throws IOException {
        File tmp = fileFactory.createTempFile();
        
        // do work on tmp ...
    }
}

Better. At least we can write a test to mock TempFileFactory, inject the mock into the ImageResizer, and validate the interactions between ImageResizer and the temporary file. But now we've burdened consumers of ImageResizer -- which simply want to resize a file -- with the requirement of managing temporary files (by creating a TempFileFactory; alternately we could have required consumers to inject a temporary file, which is probably even worse) and the awkward knowledge that ImageResizer uses temporary files. If we made a breakthrough in the ImageResizer so that it no longer needed to use a temporary file, all the consumers would need to change their code.

So how do we get the benefits of testability and isolation without this downside? We still embrace the concept of DI but use defaults to hide this from consumers, in what I call "Loose Dependency Injection"

public class ImageResizer {

    /** Package-private abstraction of temp file management */
    static class TempFileFactory {
        File createTempFile() throws IOException {
            return File.createTempFile("tmp", null);
        }
    }
    
    private final TempFileFactory fileFactory;
    
    /** Public constructor, injects its own dependency */
    public ImageResizer() {
        this.fileFactory = new TempFileFactory();
    }
    
    /** Package-private constructor for use by test */
    ImageResizer(TempFileFactory fileFactory) {
        this.fileFactory = fileFactory;
    }
    
    public File resizeImage(File image) throws IOException {
        File tmp = fileFactory.createTempFile();
        
        // do work on tmp ...
    }
}

Fundamentally we're still using DI; the difference is that there's only one implementation of the dependency, and it is "injected" by the default constructor. The consumer has no knowledge that the ImageResizer has anything to do with temporary files. ImageResizer could change to not use temporary files, and no client code would need to change. Tests for ImageResizer are easy to write because we can mock ImageResizer.TempFileFactory. The best of all worlds!