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

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

Today I had the pleasure of fixing a bug in an unashamedly-procedural ASP.NET application, comprised almost entirely of static methods with anywhere from 5-20 parameters each (yuck yuck yuck).

After locating the bug and devising a fix, I hit a wall. I needed some additional information that wasn’t in scope. There were three places I could get it from:

  • The database
  • Form variables
  • The query string

The problem was knowing which to choose, because it depended on the lifecycle of the page — is it the first hit, a reopened item, or a post back? Of course that information wasn’t in scope either.

As I contemplated how to figure the state of the page using HttpContext.Current, my spidey sense told me to stop and reconsider.

Let’s go right back to basics. How did we use to manage this problem in procedural languages like C? There is a simple rule — always pass everything you need into the function. Global variables and hidden state may be convenient in the short-term, but only serve to confuse later on.

To fix the problem, I had to forget about “this page” as an object instance. I had to forget about private class state. I had to forget that C# was an object-oriented language. Those concepts were totally incompatible with this procedural code base, and any implementation would likely result in a big mess.

In fact, it turns out to avoid a DRY violation working out the page state again, and adding hidden dependencies on HttpContext, the most elegant solution was simply to add an extra parameter to every method in the stack. So wrong from a OO/.NET standpoint, but so right for procedural paradigm in place.

November 26th, 2009 | No Comments Yet

One of the applications I work on is a planning system, used for managing the operations of the business over the next week, month and financial year.

Almost every entity in this application has a fixed ‘applicable period’ — a lifetime that begins and ends at certain dates. For example:

  • An employee’s applicable period lasts as long as they are employed
  • A business unit’s lifetime lasts from the day it’s formed, to the day it disbands
  • A policy lasts from the day it comes into effect to the day it ends
  • A shift starts at 8am and finishes at 6pm

Previous incarnations of the application simply added StartDate and EndDate properties to every object, and evaluated them ad-hoc as required. This resulted in a lot of code duplication — date and time logic around overlaps, contiguous blocks etc were repeated all over the place.

As we’ve been carving off bounded contexts and reimplementing them using DDD, I’m proud to say this concept has been identified and separated out into an explicit value type with encapsulated behaviour. We call it a Time Period:

It’s sort of like a .NET TimeSpan but represents a specific period of time, e.g. seven days starting from yesterday morning — not seven days in general.

Here’s the behaviour we’ve implemented so far, taking care of things like comparisons and overlapping periods:

/// <summary>
/// A value type to represent a period of time with known end points (as
/// opposed to just a period like a timespan that could happen anytime).
/// The end point of a TimeRange can be infinity.
/// </summary>
public class TimePeriod : IEquatable<TimePeriod>
{
    public DateTime Start { get; }
    public DateTime? End { get; }
    public bool IsInfinite { get; }
    public TimeSpan Duration { get; }
    public bool Includes(DateTime date);
    public bool StartsBefore(TimePeriod other);
    public bool StartsAfter(TimePeriod other);
    public bool EndsBefore(TimePeriod other);
    public bool EndsAfter(TimePeriod other);
    public bool ImmediatelyPrecedes(TimePeriod other);
    public bool ImmediatelyFollows(TimePeriod other);
    public bool Overlaps(TimePeriod other);
    public TimePeriod GetRemainingSlice();
    public TimePeriod GetRemainingSliceAsAt(DateTime when);
    public bool HasPassed();
    public bool HasPassedAsAt(DateTime when);
    public float GetPercentageElapsed();
    public float GetPercentageElapsedAsAt(DateTime when);
}

Encapsulating logic all in one place means we can get rid of all that ugly duplication (DRY), and it still maps cleanly to StartDate/EndDate columns in the database as an NHibernate component or IValueType.

You can grab our initial implementation here:

November 25th, 2009 | 5 Comments

Working on a legacy application that uses over 2,200 stored procedures, it can be hard to keep track of which ones are still active and which can be deleted.

Here’s a quick PowerShell script I wrote that locates stored procedures in a database that aren’t referenced by code or other database objects (assuming you have them scripted in source control).

# find un-used stored procedures
# ---------------------------------------------------------

# C# files
$src = "C:\yourproject\src"

# db objects (e.g. DDL for views, sprocs, triggers, functions)
$sqlsrc = "C:\yourproject\sqlscripts"

# connection string
$db = "Data Source=localhost;Initial Cataog..."

# ---------------------------------------------------------

echo "Looking for stored procedures..."
$cn = new-object system.data.SqlClient.SqlConnection($db)

$q = "SELECT
	name
FROM
	sys.objects
WHERE
	type in ('P', 'PC')
	AND is_ms_shipped = 0
	AND name NOT IN
	(
		'sp_alterdiagram', -- sql server stuff
		'sp_creatediagram',
		'sp_dropdiagram',
		'sp_helpdiagramdefinition',
		'sp_helpdiagrams',
		'sp_renamediagram',
		'sp_upgraddiagrams'
	)
ORDER BY
	name ASC"

$da = new-object "System.Data.SqlClient.SqlDataAdapter" ($q, $cn)
$ds = new-object "System.Data.DataSet" "dsStoredProcs"
$da.Fill($ds) | out-null

# chuck stored procs name in an array
$sprocs = New-Object System.Collections.Specialized.StringCollection
$ds.Tables[0] | FOREACH-OBJECT {
	$sprocs.Add($_.name) | out-null
}
$count = $sprocs.Count
echo "  found $count stored procedures"

# search in C# files
echo "Searching source code..."
dir -recurse -filter *.cs $src | foreach ($_) {
	$file = $_.fullname

	echo "searching $file"
	for ($i = 0; $i -lt $sprocs.Count; $i++) {
        $sproc = $sprocs[$i];
		if (select-string -path $file -pattern $sproc) {
			$sprocs.Remove($sproc)
			echo "  found $sproc"
		}
	}
}

# search in NHibernate *.hbm.xml mapping files
echo "Searching hibernate mappings..."
dir -recurse -filter *hbm.xml $src | foreach ($_) {
	$file = $_.fullname

	echo "searching $file"
	for ($i = 0; $i -lt $sprocs.Count; $i++) {
        $sproc = $sprocs[$i];
		if (select-string -path $file -pattern $sproc) {
			$sprocs.Remove($sproc)
			echo "  found $sproc"
		}
	}
}

# search through other database objects
dir -recurse -filter *.sql $sqlsrc | foreach ($_) {
	$file = $_.fullname

	echo "searching $file"
	for ($i = 0; $i -lt $sprocs.Count; $i++) {
		$sproc = $sprocs[$i];
		if ($file -notmatch $sproc) {
                	if (select-string -path $file -pattern $sproc) {
				$sprocs.Remove($sproc)
				echo "  found $sproc"
			}
		}
	}
}

# list any that are still here (i.e. weren't found)
$count = $sprocs.Count
echo "Found $count un-used stored procedures."
for ($i=0; $i -lt $count; $i++) {
	$x = $sprocs[$i]
	echo "  $i. $x"
}

It ain’t too pretty, but it does the job.

November 10th, 2009 | No Comments Yet