I’ve been reading the 37 signals book “Remote” lately and it’s got me thinking a lot about the advantages and disadvantages of working remotely.  While they clearly acknowledge that there are trade-offs to working remotely, I personally don’t think they paint a very clear picture of just how expensive those trade-offs are.  I can only really speak from a software development perspective, but I think this might apply to other types of businesses where a high degree of collaboration is necessary and the concept of “team” is more than just “a group of people”.

After 7 or 8 years of being a home-based contract-worker, and close to the same time spent working in various office environments, I’ve found that with the right people and the right environment, the office can be a lot more productive (and actually enjoyable) than a home environment, for a number of reasons.

Skype / Google Hangouts / Webex pale in comparison to actually being in the same room as someone else.  I can’t explain why, because it seems to me like it should be good enough (and I really wish it were sometimes), but the fact of the matter is that it’s not.  You miss nuances in communication that can add up to big differences in productivity.   I’ve been in hours and hours of pair programming sessions over webex: it doesn’t match the high-bandwidth of shoulder-to-shoulder pairing.  I’ve done the shared whiteboard thing: it doesn’t match the speed and simplicity of an actual whiteboard.

With communication over today’s technological mediums, there’s just a natural tendency to end the interaction as soon as possible “and get back to work” too, where people don’t actually leave Skype / Google hangouts / webex running all day long.  The result is that people are reluctant to start new conversations like that because they’re worried about interrupting the other person.  So people naturally fall back on less intrusive means of communication (text chat) and often even further back to more asynchronous forms of communication (email).

And asynchronous communication is not the boon to productivity that people think it is.  Email is today’s definitive means of asynchronous communication, but I think it’s pretty obvious that there are few methods of communication that are less efficient.  Imagine a sports team that can only communicate by email.  That would be ridiculous.  Email is amazing at its ability to cut down on interruptions of course, but it’s at the obvious cost of timeliness and immediacy (not to mention the very real human aspects including general tone and emotional nuances!).

The ideal solution would be to solve the problem of interruptions without losing timeliness.

Explaining this really requires actually defining an “interruption”:  When you’re on a team and someone wants to talk to you about the main goal of the team, that’s decidedly NOT an interruption.  Imagine a quarterback being annoyed by the “interruption” of someone yelling that they’re open for a pass.  Imagine a soldier in a firefight being annoyed at another soldier for requesting cover fire prior to some forward manoeuvring.  In order for something to really be an interruption, you have to be working on a different priority than the other person, one that you think is of higher priority.

In a collaborative environment, interruptions should often be viewed as a symptom, and not the actual cause, of the problem.  To solve the problem of interruptions at the root, you’ve got to clearly define the priorities of the team, aligning everyone on those, and concentrating as many people as possible on the top goal rather than going the easy route (management-wise) and doing something like giving each of the X members of the team one of the top X priorities, effectively “team-multi-tasking”.  Team-multi-tasking is a common approach because:

  • It’s the easiest thing to do management-wise (Why bother prioritizing when I can have X tasks worked on at once?).

  • It feels like you’re getting more done, because so many things are in progress at once.

  • It ensures everyone is 100% utilized.

But it’s also pretty obviously the absolute slowest way to get your top priority shipped and to start getting value from it  (and often the slowest way to get them all done, believe it or not!).

Not only that, but the more you do this, the more people tend to specialize into roles like “the back-end guy” or the “ops guy”, etc, and individuals lose the ability to be cross-functional, and to practice collective code ownership.  It’s a vicious cycle too: the more an individual tends toward deep specialization, the more we’re tempted to give them that kind of work because they’re the best at it.    Not only does your bus factor skyrocket, but you get back into these scenarios where anytime someone engages someone else for help, it’s an interruption to that other person, so people tend to not ask for help when they really should, or they use dog-slow asynchronous methods (like email).  Breaking this cycle means constantly trying to break down these specialty silos for any given specialty by having more experienced people collaborate with (and often mentor) less experienced people.  The end result is a team that makes full-stack engineers and not just one that hires them.

I find that the right mindset for the team is to create an environment that would be best for a team working on only 1 super-important thing that you want to start getting value from as soon as possible.  A general rule of thumb is:  If you’re having a text conversation with someone in the same room, you’re doing it wrong.  I know that’s common, but if you think about it, it’s pretty absurd.

How would that environment look?  It would be a “warroom” for radically collocating the team.  Everyone that needs to be there would be there, arranged in a manner that’s most effective for verbal communication.  There would be nearby whiteboards for collaborative design sessions, and information radiators to show the progress of the efforts and various other metrics of the current state of affairs by just glancing up.

How would the team behave?  They would be a “tiger team”.  They would all be helping to get that one thing out the door.  They would almost never use any electronic means to communicate (except obviously, when it’s more efficient, like sharing chunks of code, or urls), and you’d never hear someone say “that’s not my job”.  If someone is the only person that knows how to do something, the team identifies them as a process choke-point and quickly tries to get others up to speed on that skill or responsibility (and not by giving them links to docs or occasional hints, but by super-effective methods like pair programming, in-person demonstration, and actual verbal discussion).  If one member of the team appears to be stuck, he asks for help, and if he doesn’t, the other members notice, and jump in to help, unprompted.  There are no heroes, and everyone takes responsibility for everything that the team is tasked with.  This can and should be taken to extremes too:  members should drop their egos and make themselves available to do grunt work or testing for other members — whatever gets the top priority shipped as soon as reasonably (and sustainably) possible.  This includes making yourself vulnerable enough to ask for help from others, not only for tricky aspects of your work, but also just to divide your work up better.  If you’re taking longer than expected on a given task, you should be conscious enough of that to be openly discussing it with the team, including possible solutions, and not trying to be a hero or a martyr.  Conversely, you should never be waiting for extended periods of time for your teammate to do some work that you depend on for something else.  If a teammate is taking longer than usual, jump in and help.

How would management work then?  The team should self-organize.  With clear priorities set, the team can and should, for the most part, self-direct.  A manager should not try to manage the avalanche of interactions that happen during free-collaboration throughout the day.  Trying to manage who works on what, will simply make that manager a choke-point and slow the process down (and he/she will inevitably be wrong more than right, compared to the wisdom of the entire team).  Often a non-technical manager can have the advantage over more technical managers, because he’s forced to trust the team’s decisions and doesn’t become an “approval choke-point” for the team’s engineering decisions.

That doesn’t mean a management role is unnecessary though; it’s actually quite demanding to manage a team like this.  Priorities must always be crystal clear and for the most part, the top few priorities being worked on should not change very often.  If they do change often, you usually have either a management problem or a product quality problem.  Those problems should be fixed at the root as well, rather than making developers feel like management or customers are just a constant stream of interruptions.  Keep in mind that if you do change the top priority often enough, you can completely prevent the team from any progress at all (I’ve spent months on a team like that before — it’s not fun for anyone).  (For a more complete description of the ideal responsibilities for this style of management, see “The Management” here )

Does this work for all types of people?  No.  But then again, you’ll never get a fast team of developers without hiring the right people.  If you have people on the team that are incapable of being team-players, it’s certainly not going to work (and you’ll likely have a number of problems).

What if we have TWO top priorities though?  Flip a coin and pick one; It’s that simple.  Just arbitrarily choosing one will get one of them shipped and returning value as soon as possible.

What about team member X that has nothing to do?  The team should recognize this and:

  • try to break down the tasks better so they can help (it’s often worth a 30 minute session to bring other people on board — Any given task can almost always be broken down further with additional design discussion, even if its not worth dividing up the work).

  • try to get them pair-programming so they can learn to help better.

  • try to get them testing the parts that are done.

Obviously in some scenarios it might make sense for them to start on the second priority, but they should be ready to drop that work at any time to help get priority #1 out the door faster.  Remember: the goal is to ship finished features faster.  It’s not to keep the people on the team as busy as possible.

Isn’t that really tough on the developers to rarely have quiet time to concentrate?  Yes, at first it often is, often because focusing on the top priority requires discipline because it’s different from the status quo.  And people simply aren’t used to the buzz in the room.  The longer you spend working with headphones on, trying to carve out your own niche, separate from the rest of the team, the longer it will take you to transition and the harder that transition will be.  But soon you learn to ignore the irrelevant buzz in the room and to tune back in quickly when it’s important and relevant.  And since you’re all working on the same thing, it’s often relevant, and lot less difficult to get back into the flow state than you’d expect (especially if pair programming).  So the pay-off for developers is:

  • huge productivity improvements

  • less waiting for someone else to do their part

  • longer sessions in “flow state” and easier returns to flow state

  • less solitude without adding interruptions

  • less “all the weight is on my shoulders” scenarios

  • more knowledge sharing and personal development

It helps a lot if developers take breaks more often, because you actually end up spending a lot more time in the flow state in a given day.  You end up learning more from other developers and being vastly more productive as well, which is exhausting and energizing at the same time.  In my opinion, when done right, it’s just a lot more fun than isolated development.

Of course it often also helps to have break-out rooms for smaller prolonged conversation when desired as well.

But what if you have dozens of engineers?  It’s just not reasonable to try to make teams that contain dozens of engineers.  Brooks’ law has seemed to hold fairly well over time and he explains that one reason is that the more people you add to a group, the more communication overhead there is.  I’ve personally seen this as well, with team-size starting to get diminishing returns between  8 and 12 people, with little value (if any) to adding members beyond that.  When you get beyond 8 people on a given team, you need to start thinking about creating a second team.  Conway’s Law seems to dictate that a service-oriented architecture is the best solution we’re going to get for scaling up an organization’s developer head-count, but I’ve personally found that smaller codebases with distinct responsibilities are generally better codebases anyway.

With all that said, of course I really wish I could work remotely sometimes and get all the same benefits.  I’ve simply never seen a telepresence technology set-up that matches the fidelity of actual face-to-face and shoulder-to-shoulder collaboration.  Maybe it exists.  I’d love to hear about it.  But my experience simply doesn’t indicate that the current status quo technologies (skype, webex, etc), like Remote recommends, are up to snuff.  The way it stands today, I’ll almost always put my money on a collocated group of “team-players” over a geographically disparate team of “gurus”.

So you’re thinking about versioning your web API somehow.  Versioning is how we annotate and manage changes in software libraries, so it seems natural to re-apply this solution to changes in web APIs.  Most web APIs are versioned in order to…

(A) “freeze” an older version somehow so that it doesn’t change for older clients, or at least it is subjected to much less change than newer versions, so you can still move forward.

(B) be able to deprecate older APIs that you no longer wish to support.

(C) indicate that changes have occurred and represent a large batch of changes at once when communicating with others.

However…

(A)  Versions don’t actually solve the problem of moving forward despite older clients.

You can safely break backward compatibility with or without the concept of versions: just create a new endpoint and do what you want there.  It doesn’t need to have any impact on the old endpoint at all.  You don’t need the concept of “versions” to do that.

(B) Versions don’t actually solve the problem of deprecating old endpoints.

At best, versions just defer the problem, while forcing you to pay the price of maintaining two sets of endpoints until you actually work out a real change management strategy.  If you have an endpoint that you want to retire, you’re going to have to communicate that to all your clients that you’re deprecating it, regardless of whether or not you’ve “versioned” it.

(C)  Versions DO help you communicate about changes in a bunch of endpoints at once.  But you shouldn’t do this anyway.

Of course, if you’re retiring 20 endpoints at once, it’s easier to say “we’re retiring version 1” than to say “we’re retiring the following endpoints…” (and then list all 20), but why would you want to drop 20 breaking-change notices on your clients all at once?  Tell your clients as breaking changes come up, and tell them what sort of grace period they get on those changes.  This gives you fine-grained control over your entire API, and you don’t need to think about a new version for the entire API every time you have a breaking change.  Your users can deal with changes as they occur, and not be surprised with many changes at once (your new version).

“So how the @#$% do I manage change in my API??”

With a little imagination, it’s totally possible.  Facebook is one of the largest API providers in the world, and it doesn’t version its API.

Take Preventative measures:  Spend more time on design, prototyping, and beta-testing your API before you release it.  If you just throw together the quickest thing that could possibly work, you’re going to be paying the price for that for a long time to come.  An API is a user interface, and as such it needs to actually be carefully considered.

Consider NOT making non-essential backwards-incompatible changes: If there are changes you’d like to make in order to make your API more aesthetically-pleasing, and you can’t do so in an additive fashion, try to resist those changes entirely.  A good public-facing API should value backward compatibility very highly.

Make additive changes when possible: If you want to add a new property to some resource, just add it. Old clients will just ignore it.  If you want to make breaking changes to some resource, consider just creating a new resource.

Use sensible defaults where possible:  If you want a client to send a new property, make it optional, and give it a sensible default.

Keep a changelog, roadmap and change-schedule for your API:  If you want to solve the problem of keeping your users abreast of changes in your API, you need to publish those changes somehow.

Use hypermedia:  Tell the clients what uris to use for the requests that it needs to make and give them uri templates instead of forcing them to make their own uris.  This will make your clients much more resilient to change because it frees you up to change uris however you want.  Clients making their own uris are tomorrow’s version of parsing json with regular expressions.

NB!

Notice that almost all of these are things that you should do regardless of whether or not you version your API, so they’re not really even extra work.

Notice also that I never said “Never make changes”.  I’m not trying to make an argument against changes.  I’m just saying that versioning doesn’t help you make changes at all.  At best it just lets you put a bunch of changes in a “bucket” to dump on your API users all at once.

First the problem that we were trying to solve: we wanted a black-box integration test for our web API (which is written in node.js) to test that paging through a list of results for a collection works correctly.

Details:

  • The test framework first needs to insert a number of items (also via the API), so there are enough items for paging to come into play. The default page-size is 20, so we figured it would be worth inserting 42 items, so we’d get three pages, one of which only has 2 items.
  • The API is eventually consistent, meaning that any write to the API may or may not be readable immediately, so we need to verify that all of our writes are individually available before testing the paging.
  • The test needs to clean up after itself. What this means is that it must delete everything that it creates (in fact we also run the clean-up code before the tests run, to ensure a clean slate even in the event that clean-up failed after the last run).
  • With all of that set up complete, the test is to simply check that the three pages exist, each has 20 items on it, except the last one which has two. There is a small complication in that each page contains the link to the next page, so they naturally must be fetched serially.

Writing the test in node.js:

Despite the fact that node.js really shines at HTTP, it’s everything’s-asynch nature makes it harder to do things serially (Just like any platform that defaults to synchronous processing makes asynchronous processing more complicated). It should be pretty obvious from those 4 details above that there is a lot of necessarily synchronous processing that needs to happen.

The eventual consistency of the API made this the most complicated, because not only did we want to not move on to testing until after we’d inserted the 42 items, but we didn’t want to consider any of those items to be inserted until after they could be retrieved via GET (well HEAD is actually good enough). This basically means HEAD requesting each of the 42 items and passing that stage only after each item responds with a 200 instead of a 404 (with a timeout at some point to fail the test if this part takes too long and we can assume that a write failed). Synchronously this set-up is pretty easy:

// here’s some totally phony synchronous pseudo-code
for(var i = 0; i < 42; i++){
  var url = 'http://theapi/collection/' + i;
  response = HTTP.PUT(url, '{"some":"json"}');
  assert(response.statusCode === 202);
  // 202 means "accepted by the system, but not processed"
   response = HTTP.HEAD(url);
   while(response.statusCode !== 200){
     response = HTTP.HEAD(url);
   }
}
// NB: Errors are actually PROPERLY handled here. Any exception bubbles up automaticly and fails the test as it should.
// Afterward we move on to the actual tests, which are vastly easier to write in comparison to this set-up code

I’d love to paste our attempts at writing this asynchronously in node.js, but we deleted them about halfway through when we came to our senses. The code is so completely terrible anyway that my ego won’t let me paste it. Can I make this test work in pure node.js? Yes. But here are the cold hard facts that made us come to our senses:

  • These are tests and not a production system, so performance is largely irrelevant (within reason. I still don’t want a test suite that takes over a minute to run).
  • There’s a large amount of work that must necessarily be done serially, even if we really did care about performance.
  • This is a black-box API test which doesn’t actually test javascript directly, so we can test with whatever language/platform we want.

Writing the test in Ruby/Rspec:

Everyone knows that there are definitely languages I personally like more than Ruby that cover the same problem-space, but it’s obviously an excellent language. Rspec is an absolutely brilliant testing framework as well*. In our office, Ruby is one of our core languages, so I naturally always at least consider it for any of our problems. This was one problem where RSpec made a lot of sense, and I could paste the code for that, but it looks pretty much like a Ruby version of the fairly straightforward pseudo-code that I wrote above.

And it’s fast enough. It takes under 15 seconds for this massive test (partially because the node.js API that it’s testing is unbelievably fast!). So now we’re happily translating our black box integration tests to Ruby/RSpec.

So what did we learn?

Well, first off, let’s be clear: No one’s going to revoke my node.js fanboy card anytime soon. Node.js isn’t made to solve every problem though, and we should always try to pick the right tool for the job. There are a number of other cases where node.js wouldn’t be the first tool that I reach for either (and that’s not node.js’s “fault”)**. In this case, the problem is the complexity overhead of callbacks, which is a real thing in my opinion, but getting into that would take another post entirely (and probably will).


* HTTP clients in Ruby, on the other hand, are pretty painful (Seriously: If you’re a Rubyist and you have no problems with Ruby’s HTTP client libs, you probably have Stockholm Syndrome and should look at almost any other languages’ HTTP clients. If you start with Python’s Requests library, you can probably stop there too).


** eg: shell-scripting with node.js is also pure pain.

If you’ve ever seen a laundry list of the types of non-functional requirements like testability, accessibility, reliability, etc, (often called “ilities” because of their common suffix) you probably haven’t seen “rewritability”, but I really want to add it to the pile.

I’ve often found in software engineering that counterintuitively, if something is difficult or scary there’s a lot to be gained by doing it more often. I think we can probably agree that software rewrites are amoung those difficult and scary tasks.

Now that we’re starting to get better at service-oriented architecture, where networked applications are better divided into disparate services that individually have narrow responsibilities, a natural side effect is that it’s getting easier to write services that are replaceable later.

So what makes a piece of software rewritable?

Clearly defined requirements: not just what it needs to do, but also what it won’t do, so that feature-creep creeps into another more appropriate service. This one ends up requiring some discipline when the best place and the easiest place for a given responsibility don’t end up being the same service, but it’s almost always worth it.

Clearly defined interface: If you want to be able to just drop a new replacement in place of a previous one, it’s got to support all the integration points of the previous one. When interfaces are large and complicated this gets a lot harder and a lot riskier. In my opinion, this makes a lot of applications with GUIs very difficult to rewrite from scratch without anyone noticing (Maybe it’s because UX is hard. Maybe that’s because I’m terrible at GUIs.).

Small: Even with clearly defined requirements and interface, a rewrite is still going to be expensive and hard to estimate if there’s a lot to rewrite.

Any software engineers that have found themselves locked into a monolithic ball of mud application can see the obvious upsides of having a viable escape route though.

And once we’re not scared of rewrites, what new possibilities emerge?  Real experimentation?  Throw-away prototypes that we actually get to throw away?

How much easier is it to reason about a piece of software when it also meets all the criteria that make it easy to rewrite?

I once asked an interviewee “Ever work on a high-performing team?” and he answered “Yeah…” and then went on to explain how his team profiled and optimized their code-base all the time to give it very high performance.

That’s not what I meant, but in his defence, I really don’t think many developers have had the opportunity to work on high-performing teams and so they don’t know what they don’t know.

I’ve been developing software professionally for around 15 years and I’ve only worked on a high-performing team once. It was a couple of years ago, and it was awesome. I haven’t been able to find another since, but now I’m a true-believer in the concept of a 10X team .

I suspect that there might be groups out there somewhere who have experience with even higher-performing teams, but I’m certain that I’ve been on enough teams now that high-performing teams are extremely few and far-between. I’m not sure I even know how to create one, but I know one when I see one. I’ve definitely been on teams since that have been close to being high-performing.

The high-performing team is the ultimate win-win in the software development industry because the developers on the team are thrilled to be going into work on a daily basis and the business is thrilled because they’re producing results much faster and more reliably than other teams. Those are really the two essential criteria, in my opinion:

  1. Is everybody happy to be part of the team?
  2. Is the team producing results quickly?

The first criteria is absolutely necessary for the second to be sustainable. Any business that neglects developer enjoyment is taking a short-sighted path that will eventually negatively impact performance (due to burnout, employee turnover, etc).

So all of this sounds great, but the real mystery is in how to make it happen. I’m not 100% sure that I know. I don’t think I’ve ever even heard of people talking about how to achieve it.  This is my shot at describing the recipe though.

The Management

The craziest part of my experience is that the only time I’ve seen a high performance team happen was when the manager of the team had very little software development experience. That seems maddeningly counter-intuitive to me because from a developer’s perspective, one of the most frustrating aspects of software development is having a clueless person telling you what to do and how to do it. It turns out that being clueless in software development can be a huge benefit to being brilliant at software development management though, if the manager is already brilliant with management in general.  This manager was definitely brilliant on the management side. Here’s why:

  • He hired for attitude over aptitude. He would hire based on peoples’ potential, their attitudes, and their willingness to work hard instead of whether their precise skillset filled a niche that we needed.
  • He would cull developers who weren’t team players. It’s not a job anyone wants to do, but it’s sometimes necessary to let people go when they’re not working out. Not doing this results in the rest of the team being miserable.
  • He kept the team small, and didn’t move people in or out of it very often. This gives the team the maximum opportunity to form into a cohesive unit.
  • He would set clear goals and priorities. No two things would share the same priority (even though I’m sure he was probably secretly flipping a coin when more than one thing was extremely important). That would give the team a clear direction and an ability to focus on what’s most important.
  • He never explained a requirement with “because I said so”. This encouraged a culture of questions and feedback which enhanced learning both on the manager’s part and on the team’s part.
  • Even when priorities would change, he’d let us complete our current work where possible, so that we wouldn’t have a mess of incomplete work lying around to try to come back to later. I’ve been on teams since where the team has been repeatedly interrupted to the point of not really delivering anything for months.
  • He assigned work to the team, and not to individuals, so the team would have to own it collectively. This kept the manager from being the choke-point for “what should I work on next?” questions.
  • He didn’t make decisions or solve problems for the team that the team was able to handle themselves (even when individuals on the team would ask).
  • He’d bring us the requirements, but leave the solutioning up to us. The result was that the team was largely autonomous and in control of how it accomplished its goals, so we immediately had a newfound sense of responsibility for our work and even pride in it.
  • He’d get estimates from us, and not the reverse (ie. deadlines). This way he could inform the business about what the estimated cost and schedule for a given feature was so they could make informed decisions about what features to pursue, rather than just delivering what was finished when the clock ran out.
  • He’d actively look for scenarios where the team was not “set up for success” and rectify them.  Nothing is worse for team morale than a death march project, even a mini-one.
  • He held the team responsible for the performance of individuals. If someone on the team was struggling on a task (daily stand-up meetings make this pretty obvious) without any help from team, he’d ask the team what they were doing to help.

All of these things created the perfect climate for a high-performing team, but no one person alone (even a great manager) can create a high-performing team on their own.

The Team Member

The individuals on the team were also really impressive to me and no doubt absolutely essential to making the team what it was. Here’s a loose laundry-list of the qualities I witnessed and tried to adhere to myself:

  • Members of the team were open, honest, and respectful. They would give each other feedback respectfully and truthfully and would never talk behind each others’ backs. On other teams that I’ve worked on where this wasn’t the practice, team-crushing sub-cliques would form.
  • Once a decision has been made by the team, every member of the team would support it (even if he/she was originally opposed) until new evidence is presented. This actually worked well because we would always first take the time to actually listen to and consider everyone’s opinions and ideas.
  • Members of the team were results-oriented. “Effort” was never involved in our measure of progress. Software actually delivered according to the team’s standards was our only measure of progress.
  • The team would continuously evaluate itself and its practices and try to continuously improve them. We’d have an hour-long meeting every week to talk about how we were doing, and how we could improve (and how we were doing implementing the previous week’s improvements).
  • The team would practice collective code ownership, and collective responsibility over all the team’s responsibilities. This is actually a pretty huge deal; if people working on a top priority needed help, they’d ask for it immediately and anyone that could help would. If someone was sick, someone else would take on their current responsibilities automatically. If a build was broken, everyone would drop everything until there was a clear plan to fix it. The morning stand-up meeting would happen at exactly 9 am regardless of whether the manager was there.
  • The team would foster cross-functionality as a means of achieving collective code ownership and collective responsibility. What that meant was that members would actively try to teach each other about any particular unique skill-sets they had so that they would be redundant and team members would be better able to take on any task in the work queue.
  • The team would be as collaborative as possible. We all sat in a bullpen-like environment where we’d torn down the dividers that were originally erected between us. We’d often pair-program, not only for skill-sharing and mentoring, but also for normal coding tasks, because the boring tasks are less mind-numbing that way and the complicated tasks get better solutions that way.

In the 5 or 6 teams in our organization at the time, I think our team was by far the fastest, and most capable of handling the more technically diverse and challenging work. No one on the team was a rock-star programmer, but somehow despite that, the team as a whole was really outstanding.

Eventually when this manager moved on, I took the management role and ultimately failed to maintain that environment (partially for a number of reasons that were out of my control, and partially because at the time I didn’t realize the necessary ingredients).  I’ve only really learned them since then by watching dysfunctional teams.

It’s a cliche, but in the right environment, the collective can indeed be greater than the sum of its parts.

Suggested Hacker News title: “Show HN: I’m only 37 and I wrote this over the weekend (plus the previous ~400 days)”

First a little background

I’ve always been a big fan of REST the way Roy intended it for two major reasons:

  • It uses HTTP the way HTTP was intended, playing on its strengths and not wasting any time re-inventing what HTTP already has.
  • The state of HTTP APIs these days is really ridiculously bad, given what we should have learned from the unfathomable success of the WWW.

I was also envious as hell at the great framework Erlang developers had in Web Machine .  If you write HTTP APIs for a living and you haven’t seen HTTP mapped to a state machine, you really owe it to yourself to check it out.  It’s brilliant.

The thing I really wanted to do though was make web APIs not so terrible.  There are a few reasons that I think they’re terrible:

  • You have to read reams of documentation to do the simplest things, like finding the URL for something.
  • You have to hard-code urls all over your client app.
  • When you do something wrong, there’s no consistency in error output.
  • Knowing HTTP doesn’t make it any easier to predict how something will work.

If you rely on someone else’s API in your day-to-day work, you probably know what I mean.  I’m not going to name any names (but here’s a clue: one of the worst offenders starts with an F and rhymes with Facebook).

So the APIs I wanted to make and to use would be:

  • semantically consistent with plain old HTTP
  • discoverable, like other pages and controls on normal HTML web sites are discoverable.

Luckily HTTP is also the vanguard of API discoverability, most often in the form of hypertext (So that’s what that H stands for!) .   I’m a bit blown away that this wasn’t obvious to me earlier, but luckily I stumbled into Roy Fielding talking about hypermedia and I realized that that’s precisely the correct way to solve the discoverability problem.  He was saying real REST APIs should minimize out-of-band knowledge by leaning on what HTTP’s already got: links! * .

Then I saw Jon Moore make it real with an XHTML API .  XHTML forms are a method of discoverability as well?!? My mind was blown.  Think about that: XHTML documents tell you what kind of write-possibilities the API has.  You don’t need to read docs to find out!

And then I saw Mike Amundsen bring it all back to json   and I knew it might be something I could actually use in the real world and people trying to Get Stuff Done wouldn’t want to hunt me down and murder me in my bed (especially since I’m also a card-carrying member of the People Who Want To Get Stuff Done Liberation Front).   I think most of us are of the belief that XHTML isn’t going to unseat json as the preferred media-type for APIs anytime soon.

Armed with all this inspiration, I wrote a web-framework.  I ended up picking node.js mostly because the HTTP line-protocol stuff was already covered there without any extra cruft to get in my way, so I was free to try to aim for “Web Machine with json with links”**, which I call Percolator.  The framework isn’t the interesting part though; it’s the stuff I learned along the way, which can be done in any framework/language/platform, even if it’s not baked into the framework.

The First Interesting Part:  Hypermedia apis are indeed awesome

I started by just putting links in my json to other endpoints that make sense.  That made my json APIs so much easier to use, even when the user is me.  I had one endpoint for my entire API and every other endpoint was discoverable by following links.  I used JSONView for Chrome and for Firefox and I could click around my entire API testing the GET method on every endpoint just by clicking.  Here’s how it looks:

JSON with Links
JSON with Links


Those purple links are visited links that you can actually click on and get a new API response.  I showed some co-workers that were using my API and eventually they stopped asking “Hey what’s the URL for getting X again???”  They could always easily re-find it themselves.

Adding links also pays off when humans aren’t involved.  In many cases it means that the client doesn’t need to construct its own links.  For example: when one of my APIs was being used for replication by a client app the client developer asked how we’d handle pagination, because he wanted to page through all my results to replicate my API’s data elsewhere (sort of like how couchdb replication works, which is simple yet amazing ) .  I had a pagination scheme working, but it didn’t make use of the database indices as well as I wanted so I told him instead to just follow the ‘next’ link and not to worry about the parameters for constructing the URL at all and that the absence of a ‘next’ link would indicate the end of the results.  What this meant for me is that when I changed the pagination scheme to something more friendly to my database, I didn’t even have to tell him.  What it meant for him is that he never had to change anything on his side to support the new form of pagination, and he didn’t have to construct any urls.

It blows my mind that pushing this simple technology further could end up with clients ONLY needing to store the root URL of the API, and not a who’s-who of possible disparate endpoints that practically mirrors the routing table on the server.    People are actually starting to push the envelope this way.  Wouldn’t it be great if at some point we could stop writing client software that’s hopelessly service-dependent ?  Wouldn’t it be great if one day client-side url construction was considered as silly as using regexes to get data from json?

I should also add that even if you’re writing both the client and the server, which happens a lot with single-page apps and mobile apps, you might be tempted to think this is a waste of time, but in my experience it makes testing and debugging much easier and helps me remember what my API does after a month without using it despite my terrible memory.  That minor extra effort of adding links pays for itself over and over again.

Interesting Part #2: JsonSchema is surprisingly awesome

Of course once I could surf around my API, it didn’t take long for me to bemoan the fact that I could only peruse GETs this way.  I had seen Jon Moore’s XHTML API demo  (This is my third link to it here, so you know it’s worth a watch!) , and I was jealous of how XHTML forms could describe the POSTs as well.  Originally I decided that json needed forms as well, but the big brains in the Hypermedia-Web Google Group  convinced me that I could just expand my link concept to know about other HTTP methods.   And I had already stumbled upon JsonSchema as a way to specify what was expected in a PUT or POST payload, just like XHTML forms can do (but still using json of course).

JsonSchema is a particularly elegant solution to the problem, because I can write all my validations in JsonSchema, publish the validations as json to the api (JsonSchema is just json afterall), and then on the client side re-use them for validations before I even bother with an http request to the api.  This way I can use the same validations on the client and server, AND communicate them naturally as part of the json payload.  The end result was that my json APIs could now fully communicate everything that was possible via the json API itself.  Here’s how it looks:

JSON with POST link
JSON with POST link


I added baked-in JsonSchema support to Percolator right away of course, but you can do it easily in any of the most popular languages  ( see the validators tab).  Currently I haven’t implemented any clients that use it for validations yet, but I do use it for my server-side validations.  More importantly still, it communicates to humans everything that’s necessary for a successful PUT or POST. ***

Ultimately the addition of JsonSchema lead me to add a static frontend to Percolator that, after abstracting it away, I published separately as the Hyper+JSON Browser .  You don’t need it, but you can use it in conjunction with Percolator apps to ‘browse’ them even more easily than JSONView does (and without installing a plugin).  Any app (using any language/framework) that spits out the same sort of output as Percolator could use this the Hyper+Json Browser just the same, because it’s a static single-page app that works over any API that works similarly.  Here’s how it looks in use:

simple Browser view
simple Browser view

When you click on that ‘create’ link to POST, it does this:

Browser after clicking the POST link
Browser after clicking the POST link

That red json logo indicates that you haven’t entered valid json (yet).  Pressing OK will actually POST the json that you enter and show you the result.

Here’s a view of another resource (an individual item in the list from the previous collection resource, which can be found by clicking that item’s ‘self‘ link.  It shows delete and update links for this particular resource.

Browser after clicking one of the items in the list
Browser after clicking one of the items in the list

People have likened this to the Django admin interface, which is a huge compliment, not only because the Django admin interface is pretty legendary, but also because this frontend doesn’t know a single thing about the API other than the requirement that the API uses the aforementioned link format.  This is an area where I’m really excited: In what other ways can other programs use these APIs without foreknowledge?  (I’m not really talking about intelligent agents  – they’d need to understand a little more than the API provides — but dumber things that still use human interaction eventually, like automatic HTML form generation, are mostly possible.)

(Somewhat less) Interesting Part #3:  Object-oriented routing leads to less stupid stuff

I hate to sound old-school, but sometimes the object-oriented paradigm maps to a problem better than a functional one.  In this case, I’m talking about routing.  I don’t know why the HTTP methods GET, POST, PUT, etc are named “methods” but it sure does make perfect sense, because each one is tied to a particular “resource”: that “thing” you’re interacting with by using the HTTP methods for a given URL.  It should be obvious then that HTTP resources should be the thing we route to, and not disparate methods.  REST APIs are supposed to be the antithesis of RPC, but when routing involves the method as well, developers tend to make less RESTful APIs and framework developers tend to mess up some of the finer points of HTTP.  Here’s a quick test:

  • Grab your favorite web framework and create a resource with a single GET handler.
  • POST to it.  Did you get the proper 405 response?
  • send an OPTIONS request.  Did it tell you that only GET was available?

Probably not.  Web-machine gets this right because it routes to the resource, instead of disparate functions that when imagined together form a resource.  I wrote Percolator to work like web machine in this way, because I wanted my APIs to look like something other than a haphazard collection of RPC calls without requiring a lot of self-discipline.  The result is that Percolator responds with 405s when a client tries a method that that resource doesn’t support, and also responds to OPTIONS requests with a list of all the allowed methods.  The result again is better discoverability without reams of documentation, and better feedback for client developers when they’ve done something the API doesn’t support.

There are advantages to OO routes for application developers to though, organization-wise:

  • All routes for a particular resource are connected to that resource, so there’s no chance of sloppy intermingling in the source code.
  • A bunch of code that you have to write in each method can be written just once for the resource.
  • You start to see patterns in what resources do, which can lead to certain classes of resources that can be re-used over and over, sometimes wholesale and sometimes with particular strategies that change them slightly.  This is a bit of a big deal, in my opinion because it’s extremely rare that I see this kind of re-use in web applications in the real world.

 

Anyway:  Percolator is indeed ready for production use (at least for the use-cases for which I’ve used it in production!).   It’s extremely fast and extensible, and I hate it a lot less than anything else I’ve used for json REST APIs.

Hopefully it helps someone make a nice API, or it gives some other framework developer some new ideas.  The APIs we have today cannot possibly be the best that we can do.


* plus a pile of other conventions
** Ultimately I diverged quite a bit from Web Machine, but it was always a huge inspiration.
*** Alright not everything, but a heck of a lot.  Linked documentation on my RELs would be another huge boost to discoverability.

I’ve seen these anti-patterns in a lot of web APIs, so I thought I’d detail why they’re bad and what to do instead.

Using a 200 status code for every response:

This anti-pattern is common for SOAP-like RPC APIs.  Using a 200 status code for all your responses is silly because you end up having to reinvent an error-indication in your response body instead, and nobody in the world knows your new standard (or wants to have to learn it).

It’s also extremely confusing in the cases that an error has occurred because a status code of 200 means everything is A-OK.  There are already a bunch of error codes in the 400 and 500 ranges that are fully capable of indicating all sorts of common problems. It’s still great to put an error message in the response body, but there should be a 400 or 500-level status code so people know that an error even occurred and don’t go ahead and try to interpret the response body as normal or otherwise assume a success.

Using a 500 status code for all errors:

This anti-pattern is common because 500 is what most frameworks will do when a web application throws an uncaught exception, and so it becomes convenient to just throw exceptions and not worry about the repercussions. This is mildly better than using a 200 status code for literally everything, because at least it shows an error occurred but it still causes a lot of confusion for client developers.

When you 500 for an error (even if your web framework did it for you), you’re signalling that the problem with the request was the fault of your application (the server) and it’s possible that retrying the request will be successful. Because 500 errors indicate an internal server error, they shouldn’t actually ever happen though* — In general, you’ve got a bug in your application if they do, and the web server will tell everyone about it. The right thing to do, if there’s something wrong with the request is to respond with the appropriate 400-level status code.

Using a 500 error when a 400-level status code is more appropriate is obviously really confusing to the person making the requests because it doesn’t even let them know that their request needs to be fixed. Even if that person is also you, it forces you to start digging into your back-end for what could possibly just be a bad client request. If you don’t know which 400-level code to use, at the very least use 400 (Bad Request) itself. This will at least give your client developer an indication if the blame is on the server or the client and cut your debugging in half. A few words about the error in the response body can go a long way as well.

Logging 400-level codes at ‘error’ level:

Logging is pretty important to measuring the quality of implementation of an API, and learning about specific defects. The ‘error’ level in your logs should be a way to indicate “things that should not have happened that are within this application’s control”, so that you actually have a hope of attempting a 0-error policy. 400 level codes are errors of course, but they’re client errors, and not your server application’s error, so they should not be logged as errors along with your actual 500-level errors (Of course you might still log them as “info” level to keep track of what kinds of crazy things your clients are doing).

Why do all these details matter?

When you have an interface between two applications (the client and the server in this case) like HTTP, it REALLY simplifies things a lot if they communicate whether messages are acceptable or not (and why). Even if you control both ends of the interaction, you can save yourself a lot of server-side debugging by having the server indicate what exactly went wrong with a given request, instead of repeatedly reading stack traces every time some JSON you POSTed is missing a property. Compared to how little extra work there is involved in communicating the problem correctly, it’s pretty short-sighted to just let all exceptions bubble-up, or catch all exceptions silently (and 200).

Keep in mind too that if you’re now convinced that communicating errors is important, then HTTP already has a system for just that: HTTP status codes (plus whatever specifics you want to additionally communicate in the response body). Status codes are part of the greater HTTP standard that a lot of developers, libraries, proxies, and caches already understand. Re-inventing your own error mechanism is generally a waste of everyone’s time (with you at the top of the list).

Getting this right is a real time-saver over the long-haul even if you’re the only consumer of the API writing both client-side and server-side.  The time-savings only multiplies as you add more clients.

* Sometimes 500 is appropriate of course: If your application requires a database and its lost connectivity to it, then a 500 makes total sense. It signals that there’s a problem in your application and the client can possibly try the request again later.

If you consider the number of packages on pypi, npm, and rubygems, and the release dates of python (1991), ruby (1995) and node.js (2009), it looks a lot like those communities are getting new packages at the following rates, per year:

python:  29,720 packages / 22 years = 1351 packages per year

ruby:      54,385 packages / 18 years =    3022 packages per year

node.js  26,966 packages / 4 years =   6742 packages per year

It’s important to note that I’m only showing the other languages as a measuring stick.  There are probably a lot of reasons for the disparity here (including my imprecise math), and I’m not trying to say anything like “node.js > ruby > python”  but obviously new node.js packages are being published to npm at a staggering rate.   I just checked npm (on a Sunday night) and 20 new versions of packages have been published to npm in the last hour alone.

This is a pretty amazing feat for node.js.  How is this possible?

Batteries NOT included

If you’ve needed an HTTP client in Python, you’ve probably asked yourself “should I use urllib, urllib2, or httplib for this?” like so many people before you.  Well the answer is probably that you should use requests.  It’s just a really simple, intuitive HTTP client library that wraps up a lot of weirdness and bugs from the standard libraries, but it’s not a standard library like the others.

The “Batteries included” philosophy of Python was definitely the right approach during the mid 90’s and one of the reasons that I loved Python so much; this was a time before modern package management, and before it was easy to find and install community-created libraries.  Nowadays though I think it’s counter-productive.  Developers in the community rarely want to bother trying to compete with the standard library, so people are less likely to try to write libraries that improve upon it.

Developers are less likely to use non-standard libraries in their projects too.  I’ve heard many instance of people suffering through using an inferior standard library just to have “no dependencies”.  But in this day and age of cheap massive storage and modern package management, there are very few reasons for a policy of “no dependencies”.

Conversely, the node.js core developers seem to actually want to minimize the standard library as much as possible.  They have repeatedly removed features from the standard library to free them up to be implemented by the community instead.  This allows for the most variety and lets the best implementation win (but only until someone makes a better one, of course!).

Imagine how liberating this is for standard library maintainers too.  The node.js standard library is comparatively tiny, freeing the core developers to just deal with the core necessities.

The Tiny Module Aesthetic

Just like the 140 character limit on twitter makes people “blog” more, the node.js community has a culture of publishing tiny modules that makes people more comfortable with publishing smaller packages, and so it happens vastly more often.

While I don’t really consider myself “a node.js developer”, I’ve found myself publishing over a dozen packages in the last year myself, just because I’m working on a node.js project at work, and I publish any reusable package from that work that I create.  My project ends up factored better, and I end up with a bunch of building blocks I can re-use elsewhere (and then I do!).  Sometimes random people from the interwebs even fix my bugs before I notice them!

This approach is not unusual at all either, at least in the node.js community.  The community is lead by developers that have each published literally hundreds of packages.  I don’t even know how this is possible.

Of course there’s absolutely nothing to stop other languages from following suit, so it seems to me like community culture is the deciding factor.

Massive monolithic frameworks like Ruby on Rails tend to not take hold in the node.js community mindshare, I think due in part to this “tiny module aesthetic”, and it’s all the better for it.  It seems to me that monolithic frameworks like Rails don’t have a clear notion of what does not belong in Rails, and so they tend to expand indefinitely to include everything an application could need.  This leads to people trying to assert that Rails is the best solution for all problems, and having a cooling effect on innovation within the web application space in the Ruby community.

The tiny module aesthetic also leads to an ecosystem of extreme re-use.  When a package doesn’t do more than is absolutely necessary, it’s very easy to understand and to integrate into other applications.  Conversely, while massive monolithic frameworks tend to appear in a lot of end-user applications, they rarely never end up being dependencies in other packages themselves.  It seems unfortunate to me that so much great software should be so difficult to re-use.

git and github.com monoculture

To be honest, few things are more boring to me in software development than version control, and I find the complexity of git to be a bit silly and mostly unnecessary for me, but I’ve never heard of a node.js developer that doesn’t use it, and there’s huge value in that kind of monoculture.  It means that they all speak with a common language and there’s no impedance when you want to contribute to someone else’s projects.

Github.com has a similar effect in lowering the barriers for cross-pollination between developers.  I’ve only very rarely seen a node.js project that wasn’t on github.  This means I immediately know exactly where to find source code if I want to contribute.

The pluses and minuses of a github monoculture go far beyond this, but there’s probably enough fodder there for an entirely different post.

Permissive Licensing

Node.js packages tend to use extremely permissive licensing like MIT and BSD licensing.  In fact, the default license for a package created by `npm init` is BSD.  I think this is another sign of the times.

Very few people care anymore if someone else forks and doesn’t contribute back.  There’s very little to gain in not contributing back anyway because of the cost of maintaining your own fork.

This is important because no one wants to have to deal with dependencies that make them think about legal repercussions, or give them extra responsibilities.  Licenses like the GPL end up having a cooling effect on software-reuse for this exact reason.

If you’ve developed SaaS in a large organization (or even a small organization that acts like one), you’ve probably seen some of the symptoms of fear of releasing software:

  • Off-hours deployments and weekend deployments
  • Infrequent releases
  • extended code-freeze and testing cycles
  • Reluctance to refactor
  • Feature branches for the purpose of ‘cherry-picking’
  • release managers
  • many non-customer-facing environments before production.

These symptoms usually happen only in larger/older organizations, because of two factors:

  • They take a lot more personnel / time to implement than smaller organizations have.
  • They are usually processes and attitudes that are collected as a reaction to problems that occur in the course of a company’s lifetime.

“But you can’t be too careful!”

One problem is that you CAN indeed be too careful. It’s absolutely imperative that the costs be considered as well, if you want software development to still go reasonably fast. Otherwise these manual preventative processes will slowly creep in over time and your team will be releasing at a snail’s pace.

The other problem is that these policies alone are in some ways not careful enough. Where are the techniques for mitigating defects that inevitably still slip through? Where are the techniques to detect them, limit the customers exposed, and limit the time that customers are exposed?

All of these symptoms have a few things in common: They tend toward heavy manual and preventative process added generously over time, usually with little thought to the cost/benefit ratio of such process. It’s all too common for every production issue to result in a new process to prevent it, without regard to how infrequently that problem might occur, how damaging the result is, or how easily it is rectified.

So how do we keep bugs from getting to our customers?!?

Non-preventative measures (I call them “Reactive Measures“) do indeed exist, and can help you safely maintain a fast and steady flow of new features to customers.

  • Feature-Flags allow you to commit incomplete work to master and push it to production safely. Customer-specific feature flags allow you to test in production or enroll customers in a beta program. With a good feature-flag system, it’s even possible to release a feature to only a certain percentage of customers, and to watch your metrics to see the effects.
  • Easy/fast (read “Automated”) deployment. If deployment takes a long time, then you can’t afford to deploy often. Also, if you can’t deploy quickly, you can’t redeploy quickly (in the event of a problem).
  • Easy-undo. Rolling back from a defective release to a known-good release is the simplest and fastest way to recover from defects, if the process is both quick and easy. Defects will happen no matter how much prevention you use: Easy-undo can mean the difference between light customer impact and heavy customer impact.
  • Smaller releases. Smaller releases have less code, and therefore generally less bugs. Because they don’t contain many changes, they’re easier to test and a rollback is less-likely to negatively impact a customer. Also when a production defect appears in the latest release you have much less code to sift through to determine the cause.
  • Practice Continuous Integration (which necessarily involves always committing to master, and only incidentally has to do with using a CI server) . Feature branches, infrequent commits, and committing non-production-ready work are all practices that need to be avoided, because they are all time-consuming delaying mechanisms.
  • “Done” == “In Production”. If the team moves on to new features before the last one is in production, then that last feature is obviously unnecessarily being held back from release. They will be faster if they deliver to production and ensure it functions there properly before moving on to new features because it avoids unnecessary and time-consuming multi-tasking. This goes hand-in-hand with smaller, more frequent releases.
  • Comprehensive Automated testing. When you deploy more often, you need to test more often. The cheapest way to do this is with comprehensive automated tests. While they’re a heavy-upfront cost, if you run them as often as possible, they’ll pay for themselves very shortly.
  • Continuous Production testing. Create automated *black-box* integration tests for some of your most important features and figure out a way to run them repeatedly and continuously against your production deployment so that you know instantly when those features are broken. There’s no need to wait for customer feedback to learn about a faulty release.
  • Searchable, aggregated logging with proper log-levels. Making your logs easily searchable in one place makes them something that developers will actually use for defect detection and for debugging. They can go a long way to making your application more transparent.
  • Runtime monitoring, runtime metrics and information radiators (most importantly alerts). Instrument the things you care about most, and have alerts sent out when the measurements are abnormal.

Note: Of course some preventative processes are necessary, but when they are, automation is almost always preferable to time-consuming manual human processes.  Either way, you should consider the cost of the process and determine if it the fall-out from the type of defect it prevents is actually worth that cost.

In the end, a fear of releasing is a fear of change, and a fear of change is a fear of improvement. This is a crucial lesson that Big Company software teams can learn from the small, scrappy start-ups that are quickly trying to disrupt them. The more often you release, the more often you can test hypotheses and get customer feedback, and the more often you can course-correct. Companies that don’t realize this are susceptible to being leap-frogged by competitors that do.

I’ve been doing a lot of work with node.js recently, and since I care about testing and test coverage quite a bit, I’ve had to solve the problem of how to test classes that have what I’d call “fake-worthy” dependencies like database clients, or the file system, or network i/o (to name only a few). When I call a dependency “fake-worthy”, I mean that it’s often easier/better/faster to use a fake version of it in the tests than the real thing for a number of reasons that I won’t try to get into here.

I’ve used IOC containers on other platforms, and I’ve seen a number of ways to make require() do different things depending on whether you’re in a test environment or not. In the end, I’ve decided to just follow a simple pattern that is extremely low-tech compared to anything else I’ve seen. It should be usable in browser javascript just the same.  Here’s the skinny:

TIP #1: Pass in any fake-worthy dependencies as optional parameters.

Yes, I will change application code to make it more easily testable.
For example, if I want to test this code:

function addUserToDatabase(user){
 var db = new Database('127.0.0.1', 'someapp');
 db.insert('users', user);
}

I’ll want to test that addUserToDatabase() does its database work correctly, but I won’t want my test suite to actually hit the database:

It could instead be written as:

function addUserToDatabase(user, db){
 db = db || new Database('127.0.0.1', 'someapp');
 db.insert('users', user);
}

This let’s me do:

addUserToDatabase({name : "Joe"});

…which instantiates a new database object, because when you don’t pass a db, one gets created for you. But it also lets me do :

var fakeDB = {
 insert : function(table, obj){
   assert.equal(table, 'users');
   assert.equal(obj.name, 'Joe');
 }
}
// inject fakeDB via the second param
addUserToDatabase({name : 'Joe'}, fakeDb);

…which lets me pass in a fake database object for the purpose of testing that addUserToDatabase() calls the database correctly.

TIP #2: Don’t do anything fake-worthy in a constructor

It’s often tempting to do all kinds of initialization in a constructor so that the object is ready to use by all methods right after construction, but that can lead to problems.

For example, this code:

var CarModel = function(){
 this._db = new Database('127.0.0.1', 'someapp');
 this._db.connect(); // makes a network call to the db
}
CarModel.prototype.add = function(car){
 this._db.insert('cars', car);
}

If you don’t want to use the optional parameters trick for this constructor, you have a second option because you’re being object-oriented. You can simply call connect() outside the constructor:

var CarModel = function(){
 this._db = new Database('127.0.0.1', 'someapp');
}
CarModel.prototype.add = function(car){
 this._db.connect(); // makes a network call to the db
 this._db.insert('cars', car);
}

This makes it possible to inject a dependency using a property of the object, without changing any function signatures. Here’s an example test doing just that:

var connectWasCalled = false;
var insertWasCalled = false;
var fakeDB = {
 insert : function(table, obj){
   assert.equal(table, 'cars');
   assert.equal(car.name, 'Tesla Model S');
   insertWasCalled = true;
 },
 connect : function(){
   connectWasCalled = true;
 }
}
var carModel = new CarModel();
carModel._db = fakeDB;  // injection!
carModel.add({name : 'Tesla Model S'});
assert(connectWasCalled);
assert(insertWasCalled);

TIP #3 Use Lazily Initialization Methods

Removing fake-worthy activities from the constructor is what I’d call “Lazy Initialization”, meaning that you don’t get the dependency ready for use (db.connect() in our example) until the last reasonable moment. When you want to have a dependency lazily initialized for other methods as well, it can help to create a lazy-initialization method instead. Imagine we add a new ‘remove()’ method to our CarModel:

var CarModel = function(){
 this._db = new Database('127.0.0.1', 'someapp');
}
CarModel.prototype.add = function(car){
 this._db.connect(); // makes a network call to the db
 this._db.insert('cars', car);
}
CarModel.prototype.remove = function(name){
 this._db.connect(); // makes a network call to the db
 this._db.remove('cars', name);
}

What I would do here instead is refactor to this:

var CarModel = function(){
 this._db = null; // just to be explicit
}
CarModel.prototype.db = function(){
 if (!this._db){
   this._db = new Database('127.0.0.1', 'someapp');
   this._db.connect();
 }
 return this._db;
}
CarModel.prototype.add = function(car){
 this.db().insert('cars', car);
}
CarModel.prototype.remove = function(name){
 this.db().remove('cars', name);
}

To test add() in this scenario, I’d just substitute the _db property with our fake:

var connectWasCalled = false;
var insertWasCalled = false;
var fakeDB = {
   insert : function(table, obj){
   assert.equal(table, 'cars');
   assert.equal(car.name, 'Tesla Model S');
   insertWasCalled = true;
 }
}
var carModel = new CarModel();
carModel._db = fakeDB;  // injection!
carModel.add({name : 'Tesla Model S'});
assert(connectWasCalled);
assert(insertWasCalled);

These three patterns have made it so that I can easily deal with any fake-worthy dependencies by either monkey-patching them in or passing them as optional arguments. It doesn’t feel as clean as it could be at first because:

  • I generally try to avoid monkey-patching.
  • I usually try to avoid test-only use-cases in my application code.

I’ve decided to trade those two values away for simple testability though. While other people can wrestle with mocking frameworks that do strange things with require(), or try to devise an IoC container for javascript, I think I’ve found a methodology that won’t actually add as much complexity in the long run.

Because Javascript objects leave their internals open for access (they have no private/public access modifiers), I consider mucking with the internals to be allowed for testing purposes. I generally consider it allowed for any purpose really, because we’re all adults here, but of course for other purposes, the developer needs to know he does so at his own risk.

Once you embrace this sort of philosophy, you realize Javascript has a built-in DI framework.