Semantic CSS grid layout with LESS

Semantic CSS grid layout with LESS

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.

A wee test helper for setting private ID fields

A wee test helper for setting private ID fields

Every now and then I need to write tests that depend on the ID of a persistent object. IDs are usually private and read-only, assigned internally by your ORM, so I use a little fluent extension method to help set them via reflection.

public static class ObjectExtensions{    // Helper to set private ID    public static T WithId<T>(this T obj, object id)    {        typeof(T)            .GetField("id", BindingFlags.Instance | BindingFlags.NonPublic)            .SetValue(obj, id);        return obj;    }}

Tweak as desired to suit your naming conventions or base classes. Usage is as follows:

[TestFixture]public class When_comparing_two_foos{    [Test]    public void Should_not_be_the_same_if_they_have_different_ids()    {        var a = new Foo().WithId(4);        var b = new Foo().WithId(42);        a.Should().Not.Be.EqualTo(b);    }}

RSS: What I’m reading

RSS: What I’m reading

Lately I’ve had a few people asking for resources and links to articles about TDD and DDD. I’m a big RSS junkie, so I thought I would just share the feeds I’m currently reading.

I mostly read programming blogs, but you can see a few hints of my hidden UX aspirations as well 🙂

  • 456 Berea Street
  • A List Apart
  • Ayende @ Rahien
  • CodeBetter.Com – Stuff you need to Code Better!
  • {codesqueeze}
  • Coding Horror
  • Coding Instinct
  • Devlicio.us
  • DotNetKicks.com
  • Hendry Luk — Sheep in Fence
  • HunabKu
  • James Newton-King
  • Jimmy Bogard
  • Joel on Software
  • Jon Kruger’s Blog
  • jp.hamilton
  • Lean and Kanban
  • Los Techies
  • Paul Graham: Essays title
  • programming – top reddit links
  • Random Code
  • Scott Hanselman’s Computer Zen
  • Scott Muc
  • ScottGu’s Blog
  • Seth’s Blog
  • Smashing Magazine
  • Thoughts From Eric » Tech
  • Udi Dahan – The Software Simplist title
  • UI Scraps
  • UX Magazine
  • xProgramming.com
  • you’ve been HAACKED

Best practice DDD/TDD ASP.NET MVC example applications

Best practice DDD/TDD ASP.NET MVC example applications

It’s no secret that I’m a big fan of the ASP.NET MVC Framework. One of the reasons I like it is because it’s opinionated – instead of leaving developers free to fumble things as they choose, it recognises that most projects will be more-or-less exactly the same, and imposes some conventions to keep everyone on the same path.

This is the same philosophy used by many other application frameworks, and it saves everyone time and confusion by providing well-thought-out standards that everyone’s familiar with. However, because ASP.NET MVC is a general purpose web framework, its conventions can only cover so much — guidance for other frameworks and patterns is left to the community.

One very important area (that inspired this article) is around object-relational mappers (ORM). If I’m using the ASP.NET MVC framework:

  • How do I reference a repository from controller?
  • What’s the best way of applying a per-http-request unit of work pattern?
  • What should it look like if I’m using NHibernate? LINQ-to-SQL? etc.

Thankfully, there are a few example applications available that demonstrate solutions to these questions (and many more):

Kym NHibernate, Rhino-Commons, Castle Windsor, NUnit, Rhino Mocks, jQuery, Json.NET
S#arp Architecture NHibernate, Ninject, MvcContrib, NUnit, Rhino Mocks, Json.NET
CarTrackr Linq to SQL, Unity, MSTest, Moq, Visifire Silverlight charts, OpenID
MVC Storefront LINQ to SQL, StructureMap, MSTest, Moq, NLog, CardSpace, Windows Workflow, OpenID
Suteki Shop LINQ to SQL, Castle Windsor, NUnit, Moq, log4net, jQuery

It’s really good to see some different opinions in implementation and design, across a range of frameworks. MVC Storefront is of particular note – everything is explained over a series of 20-or-so podcasts that include interviews with well-known .NET developers like Jeff Atwood (Coding Horror/StackOverflow), and Ayende (NHibernate).

Are your applications ‘legacy code’ before they even hit production?

Are your applications ‘legacy code’ before they even hit production?

When a business has custom software developed, it expects that software to last for a long time. To do this, software must A) continue operating — by adapting to changing technology needs, and B) continue to be useful — by adapting to changing business needs.

Businesses’ needs change all the time, and all but the most trivial of software will require modification beyond its original state at some point in its life, in order to to remain useful. This is sometimes known as brownfield development (as opposed to greenfield), and from my experience, accounts for a good two thirds to three quarters of all enterprise software development.

Anyway, time for a story. A company has a flash new business intelligence system developed (in .NET) to replace an aging mainframe system. Everything goes more-or-less to plan, and the system is delivered complete and on time. It’s robust and works very well — everyone is satisfied.

Now, six months have passed since the original go-live date, and the owners have a list of new new features they want added, plus a few tweaks to existing functionality.

Development begins again. After a few test releases, however, new bugs start to appear in old features that weren’t even part of phase two. Delivery dates slip, and time estimates are thrown out the window as search-and-destroy-style bug fixing takes over. Developers scramble to patch things up, guided only by the most recent round of user testing. Even the simplest of changes take weeks of development, and endless manual testing iterations to get right. The development team looks incompetent, testers are fed up, and stakeholders are left scratching their heads wondering how you could possibly break something that was working fine before. What happened?

The illusion of robustness

The robustness of many systems like this is an illusion — a temporary spike in value that’s only reflective of the fact it has been tested, and is known to work in its current state. Because everything looks fine on the surface, the quality of source code is assumed to be fine as well.

From my experience, a lot of business source code is structured like a house of cards. The software looks good from the outside and works perfectly fine, but if you want to modify or replace a central component — i.e. a card on which other cards depend — you pretty much have to re-build and re-test everything above it from scratch.

Such systems are written as legacy code from the very first day. By legacy, I mean code that is difficult to change without introducing bugs. This is most commonly caused by:

  • Low cohesion – classes and methods with several, unrelated responsibilities
  • High coupling – classes with tight dependencies on each other
  • Lack of unit tests

Low cohesion and high coupling are typical symptoms of code written under time-strapped, feature-by-feature development, where the first version that works is the final version that goes to production.

Once it’s up and running, there’s little motivation for refactoring or improving the design, no matter how ugly the code is — especially if it will require manual re-testing again. This is the value spike trap!

The tragedy of legacy code

Back to the story. If a developer on the project realises the hole they’ve fallen into, they can’t talk about it. This late in the process, such a revelation could only be taken in one of two ways — as an excuse, blaming the original designers of the software for mistakes made today — or as a very serious admission of incompetence in the development team from day one.

The other developers can’t identify any clear problems with the code, and simply assume that all brownfield development must be painful. It’s the classic story — when granted the opportunity to work on a greenfield project, you’re much happier ó unconstrained by years of cruft, you’re free to write clean, good code. Right? But if you don’t understand what was wrong with the last project you worked on, you’ll be doomed to repeat all of its mistakes. Even with the best of intentions, new legacy code is written, and without knowing it, you’ve created another maintenance nightmare just like the one before it.

Clearly, this is not a good place to be in — an endless cycle of hard-to-maintain software. So how can we break it?

Breaking the cycle

I believe that Test Driven Development (TDD) is the only way to keep your software easy-to-modify over the long-term. Why? Because:

  1. You can’t write unit tests for tightly-coupled, low cohesive code. TDD forces you to break dependencies and improve your design, simply in order to get your code into a test harness.
  2. It establishes a base line of confidence — a quantifiable percentage of code that is known to work. You can then rely on this to assert that new changes haven’t broken any existing functionality. This raises the value of code between ‘human tested’ spikes, and will catch a lot of problems before anyone outside the development team ever sees them.

TDD gives you confidence in your code by proving that it works as intended. But object-oriented languages give you a lot freedom, and if you’re not careful, your code can end up as a huge unreadable mess.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler

So how do you write code that humans can understand? Enter TDD’s partner in crime, Domain Driven Design (DDD).

DDD establishes a very clear model of the domain (the subject area that the software was written to address), and puts it above all technological concerns that can put barriers of obfuscation between the business concepts and the code used to implement them (like the limitations of a relational database schema). The end result is very expressive entities, repositories and service classes that are based on real life concepts and can be easily explained to non-technical business stakeholders.

Plus, DDD provides a clear set rules around all the fiddly stuff like relationships and responsibilities between entities. In short, DDD is simply object-oriented code done right.

Putting it to practice

So how do you get on to a point where you can use all this? There’s a lot to learn — an entire universe of information on top of your traditional computer science/software development education. I’ve only scratched the surface here in trying to explain why I think it’s important, but if you want to learn more:

  • Read books. How many books on software development have you read this year? Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans is pretty much the DDD bible, and, just like GoF, should be mandatory reading for any serious developer. If you’re stuck in legacy code hell right now though, have a read of Michael Feathers’ Working Effectively with Legacy Code. It’s all about breaking dependencies and beating existing code into test harnesses so you can get on with improving it without fear of unintended consequences.
  • Read blogs. TDD/DDD is a hot subject right now, and blogs are great for staying on top of all the latest tools and methods. They’re also a good place for learning about TDD/DDD’s support concepts like dependency injection, inversion of control, mocking, object/relational mapping, etc.
  • Join mailing lists — DomainDrivenDesign and ALT.NET (if you’re that way inclined) are two good ones with a reasonably high volume of great intellectual discussion. You can gain a lot of insight reading other people’s real-life problems, and watching the discussion evolve as potential solutions are debated.
  • Practise. Grab an ORM, a unit test framework/runner, an IoC container and start playing around.

I believe the only way to make software truly maintainable long-term (without becoming legacy code) is to use TDD and DDD. Together, they’re all about building confidence — confidence that you can make changes to a system without introducing any bugs. Confidence that other people can understand your code and the concepts it represents. And most importantly, confidence that you’re learning, and aren’t making all the same mistakes every time you start a new project.