As you may know, I’ve recently started at a new position here in London. Last week I was pair programming all day, every day, with a couple of the other developers, learning the ins and outs of the system. It reminded me of an important tip for beginners: good pair programming requires both driver and observer to maintain focus between making a decision and implementing that change.

Renaming a class or a method can be done throughout your code in a fraction of a second with built-in IDE shortcuts. But something like promoting a static method to an injected service (still a pretty common refactoring) can easily take a couple of minutes to actually do. In this time, there’s not much going on for the observer, except listening to the sound of typing. And waiting. And trying not to get bored.

(If you’re unlucky enough to be paired with me, I’ll probably be completely distracted and playing with all the things on your desk by this point.)

Now, I am no stranger to pair programming, and have used it many times before for small tasks. But this is the first time I’ve ever done it solidly for several days at a time. This past week has been a real eye-opener for me in terms of quickly making code changes; although I have been using ReSharper for a while now, I have a new found appreciation for its keyboard shortcuts, and people who can use them effectively. Which sadly doesn’t include me yet.

Using your mouse to navigate code and poke through menus is just too slow, and it really shows when you are refactoring code in front of someone else. A good driver minimises the lag between agreeing on a change and effecting it with lighting-fast typing skills. So unplug your mouse, and go learn your tools’ keyboard shortcuts!

March 4th, 2010 | 3 Comments

In programming, correctness and robustness are two high-level principles from which a number of other principles can be traced back to.

Correctness Robustness
Design by Contract
Defensive programming
Assertions
Invariants
Fail Fast
Populating missing parameters
Sensible defaults
Getting out of the users way
Anticorruption Layer
Backwards-compatible APIs

Robustness adds built-in tolerance for common and non-critical mistakes, while correctness throws an error when it encounters anything less than perfect input. Although they are contradictory, both principles play an important role in most software, so it’s important to know when each is appropriate, and why.

Robustness

“Robustness” is well known as one of the founding principles of the internet, and is probably one of the major contributing factors to its success. Postel’s Law summarizes it simply:

Be conservative in what you do; be liberal in what you accept from others.

Postel’s Law originally referred to other computers on a network, but these days, it can be applied to files, configuration, third party code, other developers, and even users themselves. For example:

Problem Robust approach Correct approach
A rogue web browser that adds trailing whitespace to HTTP headers. Strip whitespace, process request as normal. Return HTTP 400 Bad Request error status to client.
A video file with corrupt frames. Skip over corrupt area to next playable section. Stop playback, raise “Corrupt video file” error.
A config file with lines commented out using the wrong character. Internally recognize most common comment prefixes, ignore them. Terminate on startup with “bad configuration” error.
A user who enters dates in a strange format. Try parsing the string against a number of different date formats. Render the correct format back to the user. Invalid date error.

(Important side note: Postel’s law doesn’t suggest skipping validation entirely, but that errors in non-essential items simply be logged and/or warned about instead of throwing fatal exceptions.)

In many cases, relentless pursuit of correctness results in a pretty bad user experience. One recent annoyance of mine is companies that can’t handle spaces in credit card numbers. Computers are pretty good at text processing, so wasting the user’s time by forcing them to retype their credit card numbers in strange formats is pure laziness on behalf of the developer. Especially if you consider the validation error probably took more code than simply stripping the spaces out.

Compare this to Google Maps, where you can enter just about anything in the search box and it will figure out a street address. I know which I prefer using.

Robustness makes users’ lives easier, and by doing so promotes uptake. Not only amongst end users, but also developers — if you’re developing a standard/library/service/whatever, and can build in a bit of well thought-out flexibility, it’s going to grant a second chance for users with clients that aren’t quite compliant, instead of kicking them out cold.

Adam Bosworth noted a couple of examples of this in a recent post what makes successful standards:

If there is something in HTTP that the receiver doesn’t understand it ignores it. It doesn’t break. If there is something in HTML that the browser doesn’t understand, it ignores it. It doesn’t break. See Postel’s law. Assume the unexpected. False precision is the graveyard of successful standards. XML Schema did very badly in this regard.

HTTP and HTML are displaying robustness here; if they see anything they don’t recognize they simply skip past it. XML Schema on the other hand fails validation if there are any extra elements/attributes present other than precisely those specified in the XSD.

Correctness

So robustness makes life easier for users and third-party developers. But correctness, on the other hand, makes life easier for your developers — instead of bogging down checking/fixing parameters and working around strange edge cases, they can focus on the one single model where all assumptions are guaranteed. Any states outside the main success path can thus be ignored (by failing noisily) — producing code that is briefer, easier to understand, and easier to maintain.

For example, consider parsing XHTML vs regular HTML. If XHTML isn’t well formed, you can simply throw a parser error and give up. HTML on the other hand has thoroughly documented graceful error handling and recovery procedures that you need to implement — much harder than simply validating it as XML.

Which should you use then?

We have a conflict here between robustness or correctness as a guiding principle. I remember one paralyzing moment of indecision I had when I was a bit younger with this very question. The specific details aren’t important, but the 50/50 problem basically boiled down to this: If my code doesn’t technically require this value to be provided, should I check it anyway?

To answer this question, you need to be aware of where you are in the code base, and who it is serving.

  • External interfaces (UI, input files, configuration, API etc) exist primarily to serve users and third parties. Make them robust, and as accommodating as possible, with the expectation that people will input garbage.
  • An application’s internal model (i.e. domain model) should be as simple as possible, and always be in a 100% valid state. Use invariants and assertions to make safe assumptions, and just throw a big fat exception whenever you encounter anything that isn’t right.
  • Protect the internal model from external interfaces with an anti-corruption layer which maps and corrects invalid input where possible, before passing it to the internal model.

Remember if you ignore users’ needs, no one will want to use your software. And if you ignore programmers’ needs, there won’t be any software. So make your external interfaces robust. Make your internal model correct.

Or in other words: internally, seek correctness; externally, seek robustness. A successful application needs both.

February 10th, 2010 | 5 Comments

Announcement: in just over a fortnight I’ll be packing my bags to go chase the kiwi dream – I’m moving to London!

Provoke has been a wonderful home for the past two years, and I thank all my workmates and clients who made my time there so special. Working here has really been an unforgettable experience, and I hope to take a little bit of that magic onto future jobs and organisations.

So far, my immediate plan for the next few months involves .NET architecture/development work in London, probably on contract basis so I can fit in some travel around Europe between projects. I’m also keen to check out the various developer conferences like QCon and Oredev. But first, I need to start packing!

January 18th, 2010 | 4 Comments

I have a confession to make. After eight years since we first met, I still don’t quite get CSS.

Sure, I can do typography, sprite backgrounds and understand the basics of the box model. I even know about browser-specific CSS extensions for CSS3 effects. But when it comes to clearing floats, vertically-aligning form elements or figuring out inline parents with block children, I go to a very dark place and start cursing.

I freely admit my CSS layout and positioning skills are lacking, and I probably shouldn’t even be blogging about it. But when I discovered CSS grid frameworks, I was naturally interested — anything that helps me get up and running quicker in a foreign language is a win.

Grid frameworks: CSS for dummies

For those that don’t know, grid frameworks like 960gs, YUI grids and Blueprint CSS provide a simple 12, 16 or 24 column grid that abstracts away complicated CSS layout and positioning rules.

For example, using the Blueprint CSS framework, this markup produces the following layout, neatly centered in the middle of the browser window:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="blueprint/screen.css" />
</head>
<body>
    <div class="container">
		<div class="push-4 span-15">header</div>
		<div class="push-4 span-4">menu</div>
		<div class="span-7">main</div>
		<div class="span-4">ad space?</div>
		<div class="push-4 span-15">footer</div>
    </div>
</body>
</html>

How easy was that? As a CSS newbie, not having to worry about floats, clears, negative margings and other positioning tricks is a very attractive proposition.

So CSS grids are very powerful for quickly laying out elements. But there is a trade off you should consider — HTML marked up with grids is not at all semantic. Peppering your HTML with classes like .span-12 or .yui-t3 for layout is no better than specifying table widths and heights everywhere.

Wouldn’t it be great if you could keep using these grid classes, but somehow mask them behind semantic class names?

LESS: CSS preprocessor

About the same time I discovered grids, I stumbled upon LESS: a ‘leaner’ CSS command-line preprocessor that extends CSS with its own syntax and features. The .NET port, .Less, has a smaller feature set than the rails version, but it lets you do stuff like this:

.rounded_corners {
	@radius: 8px; /* variables */
	-moz-border-radius: @radius;
	-webkit-border-radius: @radius;
	border-radius: @radius;
}

#header {
	.rounded_corners; /* mix-ins */

	img.logo { /* nested styles */
		margin: (@radius * 2) + 1px; /* expressions */
	}
}

#footer {
	.rounded_corners;
}

I have .Less is setup as an HttpModule in my web.config. It intercepts any requests to *.less files, translates them to real CSS, and optionally minifies (compresses) them. So you can you can simply reference the .less file directly in your markup, with no extra compilation step required:

<head>
    <link rel="stylesheet" type="text/css" href="site.less" />
</head>

Grid CSS frameworks + LESS = semantic grids

I’ve been using LESS for a few weeks now, and to be honest, I never want to go back to writing ‘raw’ CSS again. So what happens when you combine the CSS grid framework with LESS? Here’s the new stylesheet:

@import blueprint/screen.css;

div.container {

	div.header {
		.push-4;
		.span-15;
	}

	div.menu {
		.push-4;
		.span-4;
	}

	div.main {
		.span-7;
	}

	div.ads {
		.push-4;
	}

	div.footer {
		.push-4;
		.span-15;
	}
}

All that’s left is semantic class names using grids styles as mix-ins. Now the markup is looking acceptable again:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="site.less" />
</head>
<body>
    <div class="container">
		<div class="header">header</div>
		<div class="menu">menu</div>
		<div class="main">main</div>
		<div class="ads">ad space?</div>
		<div class="footer">footer</div>
    </div>
</body>
</html>

Using grid classes as mix-ins gives us the best of both worlds — you get the power of the grid CSS framework, but without introducing layout concerns to your markup.

December 28th, 2009 | 3 Comments

Here’s a couple of real-life documentation examples from a system I’ve been building for a client:

A Monitored Individual is a role played by certain Employees. Each Monitored Individual is required to be proficient in a number of Competencies, according to [among other things] what District they’re stationed in.

A Training Programme is comprised of Skills, arranged in Skill Groups. Skill Groups can contain Sub Groups with as many levels deep as you like. Skills can be used for multiple Training Programmes, but you can’t have the same Skill twice under the same Training Programme. When a Skill is removed from a Training Programme, Individuals should no longer have to practice it.

This is the same style Evans uses himself in the blue DDD book. A colleague jokingly called it Domain-Driven Documentation.

I adopted it after noticing a couple of problems with my documentation:

  • I was using synonyms — different words with the same meaning — interchangeably to refer to the same thing in different places.
  • Sentences talking about the code itself looked messy and inconsistent when mixing class names with higher-level concepts.

It’s a pretty simple system. There are only three rules to remember: when referring to domain concepts, use capital letters, write them in full, and write them in bold.

Highlighting the names of domain concepts like this is a fantastic way to hammer down the ubiquitous language — the vocabulary shared between business and developers.

Since adopting it, I’ve noticed improvements in both the quality of my documentation, and of the communication in our project meetings — non-technical business stakeholders are starting to stick to the ubiquitous language now, where in the past they would fall back to talking about purely UI artifacts. This is really encouraging to see — definitely a success for DDD.

December 10th, 2009 | 3 Comments