September 17th, 2012

TDCSS.js

Posted in Ikke kategoriseret |

Test driven CSS development

I’m a huge fan of test-driven development!
Almost every day, I make use of unit tests when writing Javascript. TDD helps me focus my development on singular tasks, and it enables me to easily verify that all my stuff works after refactorings or other kinds of changes.

One day I thought: “Why don’t we have this for CSS?”.

CSS – especially for large projects with many developers – is a major pain!
There are no clear-cut rules for modularity, the inheritance mechanisms are obscure, and the runtime environments (the browsers) are still no way near consistent in their interpretations of style rules.

It occurred to me that TDD methodology would be a great way to tackle these problems.

Enter tdcss.js

What I wanted was a way to specify UI elements in an isolated context – similar to the “units” in unit testing, so I could apply my styling and continuously verify that already styled elements still looked like expected. This would also force a modularity focus onto my CSS which is highly desirable when working on big projects.

I won’t go into details about the implementation in this post.
Here’s a screenshot of the tdcss test-suite together with the HTML code that generates it.

<!-- # Box styles -->
 
<!-- : Basic box -->
<div class="box">
    <p>This is a basic box.</p>
</div>
 
<!-- : Notice box -->
<div class="box-notice">
    <p>This is a notice box.</p>
</div>
 
<!-- : Warning box -->
<div class="box-warning">
    <p>This is a warning box.</p>
</div>
 
<!-- : Alert box -->
<div class="box-alert">
    <p>This is an alert box.</p>
</div>
 
 
 
<!-- # Typography -->
 
<!-- : H1 -->
<h1>This is an H1 header.</h1>
<!-- : H2 -->
<h2>This is an H2 header</h2>
<!-- : H3 -->
<h3>This is an H3 header</h3>
 
 
 
<!-- # Custom height -->
 
<!-- : Some element that needs a lot of space; 700px -->
<h3>This is a test.</h3>

Demo screenshot

Go to https://github.com/jakobloekke/tdcss.js for instructions on how to use it – and to download it, of course. :)

flattr this!

May 23rd, 2012

Specs and creativity

Posted in Code, Creativity |

Today I became aware of the existence of the Joel Test – a list of questions for assessing the quality of a software development team:

  1. Do you use source control?
  2. Can you make a build in one step?
  3. Do you make daily builds?
  4. Do you have a bug database?
  5. Do you fix bugs before writing new code?
  6. Do you have an up-to-date schedule?
  7. Do you have a spec?
  8. Do programmers have quiet working conditions?
  9. Do you use the best tools money can buy?
  10. Do you have testers?
  11. Do new candidates write code during their interview?
  12. Do you do hallway usability testing?

I was puzzled by number 7: “Do you have a spec?”, but soon found out that it just means: Do you write specs before coding?
(Fair enough. I thought “spec” meant something else in this context.)

Joel explains:

“Writing specs is like flossing: everybody agrees that it’s a good thing, but nobody does it.
I’m not sure why this is, but it’s probably because most programmers hate writing documents. As a result, when teams consisting solely of programmers attack a problem, they prefer to express their solution in code, rather than in documents. They would much rather dive in and write code than produce a spec first.”

I feel that way exactly!
I know specs are an important alignment tool when communicating with team members – to keep everyone on the same page, so to speak.
But they’re boring to write, and I often have the feeling that the spec writing process takes away an important creative aspect of programming. They tend to make you avoid the unknown and take the safe road.
We are often told that programming is a creative endeavor and this is very true.

But why is the creative aspect valuable?
One of the things that characterizes other creative fields – such as art or music – is that the artist tends to draw inspiration from the interaction with his or her tools. This inspiration is often a key source of innovation. I bet you Jimi Hendrix didn’t plan on his guitar sounding like that the first time he accidentally cranked up the gain too much and made it feed!
But he saw the potential and made rock history with that sound.

I’m certainly no Jimi Hendrix, but I do know this kind of creative process first hand:
When I’m working on music, I would, for instance, never dream of having a spec!
Instead, what I do is keep my ideas microscopic, then try them out and get something more or less unexpected in return from my machines. Typically, hearing this will spark a new idea in my head, and so in a prolonged, iterative process, I’ll produce a piece of music in close collaboration with my collection of electronic equipment. The result is completely unknown, until it’s suddenly deemed finished.

Of course, that kind of uncompromised creative flow is not viable in a business context – and I’m sure more commercially successful musical artists than me have some way of sneaking a “spec” or a plan into the process in order to keep their productivity high. Inspiration is quite unreliable at times. Any artist will tell you that!

But when it comes to programming, where do we draw the line?
How do we keep control of our productivity, while still keeping our process open to the kind of sudden inspirational insights that fuel innovation?

flattr this!

April 26th, 2012

Growing software

Posted in Code |

Next time you refer to software development as “building” something, there’s a good chance that you’re doing damage to your project.

The construction metaphor is widespread in software and IT, and there are several reasons why:

  • It sounds like you are creating a thing which can be assessed on its’ own in absolute terms – detached from the social reality of its’ inhabitants or users.
  • It sounds like you are doing something, which will eventually be finished.
  • It makes software engineers and architects seem more like “real” engineers and architects.

All of this sounds very serious and reassuring to clients.

But the worst threat to problem solving is misunderstanding the nature of the problem.
And software is nothing like buildings!

  • Software is social. Content and data is created by people. Business rules are described and used by people and reflect (and change with) the organization in which they are embedded.
  • Software is never finished. There’s always a next version, a “phase two”, a redesign, etc. somewhere on the horizon. And if you’re lucky enough to work on agile projects, this flow of re-alignments is even more accellerated.
  • Job titles in the software industry sometimes seem like they’re meant solely to describe our work in terms our grandmothers can understand. In reality, the titles don’t say much about the nature of the jobs.

Software gardener

Today I stumbled on this great collection of some of the many, many software development laws.
The author of the post notes that: “some of the laws come from the world of biology — they also appear in some lists of software laws, and I think they still apply.
This observation brilliantly emphasizes why the gardening metaphor (suggested by Andrew Hunt and David Thomas ) suits the art of software development much better than the construction metaphor.

Gardening is about thinking ahead, planning, then waiting patiently and reacting to the ways of nature, nursing, killing bugs and weeds – and season after season learning from your experience.

Good software is created in the same way: Pre-planning using as many skills as possible, then trying out concepts and ideas in real life, nursing and improving what works and getting rid of what doesn’t – then going back and doing it again and again.
Good programmers – like good gardeners – know when to immerse themselves in little things and when to take a step back and assess the grand perspective. They understand the intimate connection between the singular detail and the ecosystem.

We already talk about “growing businesses”, so the concept of growing software shouldn’t be hard to explain to clients or investors.

Btw.: As with any interesting topic, Jeff Atwood has written a quality piece about this over at codinghorror.com.

flattr this!

February 24th, 2012

Benchmarking the jQuery DOM ready binding

Posted in Code |

After a discussion with a colleague about the pros and cons of using a lot of $(document).ready(function(){ … }) statements across a project, I decided to measure the raw performance of the event binding itself.

Both of us agreed that extensive use of this statement represents a sort of code-smell – that it’s probably a sign that your Javascript needs better structure – and that this, in turn, will probably lead to bad performance in one way or another.

But that set aside, how about the statement itself?
Does it incur a performance hit?

Here’s the code I used for testing:

var no_of_bindings = 100;
 
function bind(){
    for (var i = no_of_bindings - 1; i >= 0; i--){
        $(document).ready(function(){ });
    };
};
 
console.time("bindings");
bind();
console.timeEnd("bindings");

For IE, I used Firebug Lite, which supports the console.time method.
All times are measured in milliseconds.

And here are the results:

Number of bindings: 1 10 100 1000 10000 100000 1000000
Firefox 1 1 5 12 109 1052 4952
Chrome 0 0 0 2 17 160 1936
IE9 0 2 5 16 140 1831 16866
Safari 0 0 1 6 63 872 8739

As it turns out, you need to do an absurd amount of bindings before the performance overhead is worth caring about – even for IE.
It might be different for older browsers, of course, but I didn’t feel like bothering with measuring those, since the pattern is probably equal + you have loads of other things dragging you down.

So in conclusion: DOM ready bindings are almost free to do, but you should of course still be conscious about why you are using them.

flattr this!

November 22nd, 2011

How to use Knockout.js with XSLT

Posted in Code |

As you may know, Knockout.js uses inline Javascript for it’s elegant, declarative bindings:

<li data-bind="css: {'active': visible()}"></li>

But if you use XSLT to render your HTML, it may fail because the curly-braces may not be supported in attributes.

To make this work, you need to do two things:

  1. Convert the attribute:

    data-bind="..."

    into an

    <xsl:attribute name="data-bind">

    Like this:

    <li>
     <xsl:attribute name="data-bind">
      css: {'active': visible()}
     </xsl:attribute>
    </li>
  2. Do a search and replace exchanging the curly braces with XML-safe entities:
    	"{" to "&#123;"
    	"}" to "&#125"

    So the final XSLT should look like this:

    <li>
     <xsl:attribute name="data-bind">
      css: &#125'active': visible()&#125
     </xsl:attribute>
    </li>

     

Ugly, I know! But now it will work.

flattr this!

September 20th, 2011

DropCheck: A magic checklist using Dropbox and Knockout.js

Posted in Mobile |

Ever created a todo list in a .txt file, then popped it into Dropbox for iPhone viewing?

I do it all the time! That’s why I created DropCheck.

 

DropCheck

DropCheck is a web app that turns lines in a .txt file into checkable lines in a nice web app interface.

It’s tailored specifically for grocery shopping, as this is a common use case for me.
You have the ability to tick off each item as it goes in your shopping cart (“Yes”).
Or you can mark it as sold out (“No”).

At the bottom you can move the checked items to the bottom of the list, so you have them out of sight.
The web app also remembers the state of the list even though you close it.
To re-connect to the Dropbox .txt-file you just click the “Reset to Dropbox file” link.

Installation:

To install, unzip the DropCheck folder into your Dropbox public folder, then get the public link of the file called dropcheck.htm:

 

Visit the public URL in Safari on your iPhone and save it to your homescreen:

    

 

Now, when you visit the DropCheck app, you’ll see the contents of the dropcheck-list.txt file turned into a checkable list.

Enjoy!

 

UPDATE for Windows users:

Kasper Hyllested pointed out to me, that there was an issue with international characters when saving the .txt-file from Notepad on Windows.

To fix this, you must force notepad to save using UTF-8 encoding of characters (instead of ANSI):

flattr this!

October 8th, 2010

How to make CSS3PIE work

Posted in Code, Design |

CSS3pie

Countless hours have been lost creating rounded corners, dropshadows and gradient backgrounds for the web.
With Internet Explorer still lacking support for CSS3, until recently it seemed like we would have to keep doing tiny graphic sprites (or implementing dirty javascripts) in order to accomodate the demand for such UI niceness.

Enter: http://css3pie.com/
PIE is a .htc CSS behaviour script that enables support for dropshadows, rounded corners and background gradient CSS3 properties in Internet Explorer – all the way back to IE6!

Of course, I couldn’t wait to try it out.
And it didn’t work.
Bummer …

Fortunately, I found out why:
It only works on positioned elements.

You must specify “position: relative;” or “position: absolute;” on the element that calls the .htc behaviour, and then it works!

Amazing script!
CSS3 future is here now.
Thank you so much, Jason Johnston of 327 Creative LLC, for sharing this little goodie with the world!

flattr this!

February 16th, 2010

Useful PHP libraries, part 2 – Scaffold CSS

Posted in Code |

NOTE: This post describes a library which has been discontinued. These days I use SASS instead.

Scaffold CSS was developed by Anthony Short and it is every CSS-coder’s dream come true:

Variables, nested selectors, abstractions from vendor-specific properties etc. etc. etc. Good stuff!

Installation and usage couldn’t be simpler! (Really. I don’t see how it could!)
You place the library folder in whatever folder holds you CSS-files. Then you copy-paste the .htaccess-file that redirects every request for your CSS-files to the library. Scaffold then reads through your CSS and interprets whatever tricks you’ve written and serves up nicely formatted (or minifed, if you prefer) W3C-compliant CSS.

”What’s this good for?”, you say?

Well. Consider this piece of regular CSS:

form#searchbox #arrival_date,
form#searchbox #departure_date,
form#searchbox #persons,
form#searchbox #location
{
font-size: 18px;
color: white;
margin-bottom: 20px;
}
form#searchbox #arrival_date label,
form#searchbox #departure_date label,
form#searchbox #persons label,
form#searchbox #location label
{
width: 100px;
display: inline-block;
}
form#searchbox #arrival_date input,
form#searchbox #departure_date input,
form#searchbox #persons input,
form#searchbox #location input
{
font-size: 18px;
width: 180px;
height: 40px;
padding-left: 10px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
behavior: url("boxsizing.htc");
}
form#searchbox #arrival_date .popupcalendar_icon,
form#searchbox  #departure_date .popupcalendar_icon,
form#searchbox  #persons .popupcalendar_icon,
form#searchbox  #location .popupcalendar_icon
{
background: url(./graphics/images/sprites.png) no-repeat 0 0;
height: 295px;
width: 314px;
display: block;
text-indent: -9999px;
overflow: hidden;
background-position: -271px -20px;
height: 39px;
width: 31px;
zoom: 1;
display: inline;
display: -moz-inline-box;
display: inline-block;
vertical-align: top;
margin: 3px 0px 0px 10px;
}

Even though it’s nicely ordered and very readable, this code is still quite hard to understand at first look. You can’t just read what’s going on. What’s related to what? You need to look back and forth a few times to see this.
This makes it bad code!
Good code is always easy to read and understand.

Now look at the same code in Scaffold syntax:

@constants {
   labelTextColor: white;
   gutter: 10px;
}
 
form#searchbox {
 
   #arrival_date, #departure_date, #persons, #location  {
      font-size: 18px;
      color: !labelTextColor;
      margin-bottom: #[2 * !gutter]px;
 
      label {
         width: #[10 * !gutter]px;
         +inline-block();
      }
 
      input {
         font-size: 18px;
         width: 180px;
         height: #[4 * !gutter]px;
         padding-left: #[1 * !gutter]px;
         +border-box();
      }
 
      .popupcalendar_icon {
         image-replace: url('./graphics/images/sprites.png');
         background-position: -271px -20px;
         height:39px;
         width: 31px;
         +inline-block();
         margin: 3px 0px 0px 10px;
      }
   }
}

The nesting immedietaly makes the code easy to read!
The selectors come in a logical order. The code is scannable, and in my opinion this is quite a revolution as far as CSS goes!

And it gets even better!

As you may have noticed, my second code example is full of non-CSS properties.
These are Scaffold-specific functions, constants and ”mixins”.

For example: A standard gutter width of 10px is defined as a constant, then used throughout the style declarations by reference.
No more search-and-replace for simple color changes!
This feature alone will save me countless hours.

Then there’s stuff like ”+inline-block();” or ”+border-box();”. These are ”mixins” that basically call a set of CSS properties that take care of crossbrowser compatibility. Scaffold serves up vendor-specific properties and even a selection of IE-behaviors, filters and expressions to get the desired effect working all around. Now we have a one line trick that’ll fix box model-quirks or get inline-blocks behave like expected. (Or rotation, shadows and other CSS3-goodies for that matter). This means more time for coffee, which is nice!

Finally we have functions like ”image-replace: url(‘./graphics/images/sprites.png’);”
This line takes care of everything regarding CSS image replacement. It even automatically sets the correct height and width fitting the specified image file.

The library has tons of useful features and some pretty advanced ones too. Everything is cached, so it’s just as fast as regular CSS.

So if you’re lucky enough to have your CSS-files served from an Apache server with PHP enabled, then by all means, do not miss out on Scaffold CSS!

flattr this!

February 3rd, 2010

Useful PHP libraries, part 1 – SLIR

Posted in Code |

In this series of blog posts I introduce my favourite PHP libraries.

Today’s library is:
SLIR

SLIR – or ”Smart Lencioni Image Resizer” – was developed by Joe Lencioni.
It does on-the-fly scaling and cropping of images.

The benefit is that you can change your image sizes dynamically on request-time.
If your page layout changes, you can just request images with new sizes that fit.

Under the hood it’s a clever PHP script that returns the content of an image file. Requests are handled by a .htaccess-file that disguises the underlying PHP and presents it to the public as an actual image file.

This means you activate the resizer just by requesting a url with some resize parameters plus the path to the original image file.

Example:

Original image:

<img src="http://www.jakobloekkemadsen.com/wp-content/uploads/2010/02/DSC_1225_maj-30-2009.jpg" alt="" />

Scaled to fit 100px width:

<img src="http://www.jakobloekkemadsen.com/slir/w100/wp-content/uploads/2010/02/DSC_1225_maj-30-2009.jpg" alt="" />

Scaled to fit 25px width and cropped to square:

<img src="http://www.jakobloekkemadsen.com/slir/w25-c1:1/wp-content/uploads/2010/02/DSC_1225_maj-30-2009.jpg" alt="" />

”What about performance?”, I hear you ask. “Won’t the server choke on having to process all image requests?”

No, it won’t. (-:
SLIR caches the image the first time it’s requested, so all subsequent requests are served just as fast as any other image file on the server. The redirect is handled by an alias to the cachefile. Only if no matching cache file exists, or if it’s too old, or if the original has changed, then SLIR is invoked and a new image is generated and cached.

”Ok. But what about security, then?”

In theory this script enables a hacker to flood your server with files just by changing the url and requesting all imaginable combinations of width and height. This issue has been discussed in the comments on http://shiftingpixel.com/2008/03/03/smart-image-resizer/ and the current version of the script can be made to restrict access to any other combinations than the ones you specify.

Personally I haven’t found an easier, more futureproof and flexible solution for handling image scaling.
And it’s free!

Simply put: I love this script!

Stay tuned for part two of “Useful PHP libraries”. Coming soon …

flattr this!

January 10th, 2010

What’s with the painting?

Posted in Art |

Edit: At the time of writing, the Albrecth Dührer painting was used in the design of this site.
This has been changed since.

The background painting on this page is by the German painter Albrecht Dürer (1471 – 1528).

It’s from 1503 and the title of the painting is ”Das große Rasenstück” or ”The Large Turf”.

I decided that I wanted a real painting for the background, so I browsed around the web, came across this one and loved it instantly. It has amazing details in both color and perspective. And the colors made a nice palette for the rest of my design.

Considering the paintings’ year of origin, it’s incredibly modern looking!

It does have this special pre-renaissance or late medieval feel about it, though (those who read Foucault – ”The order of things” will probaby know what I mean). There’s something about the way the whole setting is illuminated that gives it a magical edge.

Here are some more pictures by Dürer:

“Porträt Albrecht Dürer der Ältere” (1490) is your typical 15th century portrait.

Not too interesting. Rembrandt is the place to look for interesting portraits.

Weiher im Walde” (1495) is more interesting:

The brush strokes and colors remind me of van Gogh and at first glance one could easily read this picture into the present day debate about man-made pollution vs. Nature.

It looks almost like chimneys to the left sending agressive black smoke into the forrest to the right.

I love it when old works of art suddenly ressemble something that wasn’t around when they were made:

Or how about “Feldhase” (1502) – this could be an illustration in a modern encyclopedia. Very impressive and realistic! I could be fooled if someone told me it was 20th century:

“Melancholia I” (1514)  is much less naturalistic, but instead it has this almost Picasso-like avant garde quality about the composition – with its interwoven shapes and the twisted perspective. Quite impressive, I think:

And here’s my personal favourite: “Rhinocerus” (1515).

I think the rhinos’ facual expression is priceless! (-:

“Wrap it up, dude! Nature calls …”

More about Albrecht Dürer:

flattr this!