Is Time Relative in JavaScript?

JavaScript’s setInterval() and setTimeout() functions allows us to execute JavaScript code at specific time intervals. In most cases the timer and your code works intuitively. The single thread and other language behaviour protects most JavaScript developers. Nevertheless it is very important to understand the fundamentals of JavaScript timers.

Using setInterval and setTimeout

Let’ start by showing how to use these functions. There are two ways of setting up a timer:

var timerId = setTimeout(fnCallback, delayInMilliseconds);

This will call the callback function once after an delay in milliseconds.

var timerId = setInterval(fnCallback, intervalInMilliseconds);

And this will call the callback function continously every given interval time span.

To stop a timer use the function clearInterval() with a timer id. Like

clearInterval(timerId);

Timer Accuracy and the Event Queue

There is no guarantee that the fnCallback function is called at a specific timer delay. This is based on the single thread execution and the concept of the event queue. Single thread means that JavaScript can only execute one piece of a code at a time. Every event, like a simple mouse click or more complex like drawing the page, seams to be asynchronous, but they are all organized within the event queue.

To make it clearer the following diagram demonstrates it.

Example of a JavaScript event queue.

Every piece of code (function) is put into the queue. If one block of code needs more time to execute, then everything else will be delayed. The above figures shows an example of it. @0 a interval is initialized. Let’s assume that the code is still ongoing and a mouse event occours @200. @300 the code execution is completed. The next one will be the code for the mouse event, because it was placed to the queue earlier then the interval code. In the end the interval code execution  startet @400 with a 100ms delay.

So never rely on exact timing behaviour. If we are planning to do some animations or a game then we have to measure the time between two interval codes to calculate a correction coefficient for ourwork. For more about game loops take a look at this article “The Game Loop”.

What happens if the callback function takes longer?

Longer than the interval time. For example we have a interval time of 100ms, but the code execution needs 200ms. @100 the first interval code is starting. @200 the next interval wants to run, but it is queued in and waiting. (remember single thread). @300 there can happen different things: the second interval code can be started or another code, like an event handler, will be executed. So again, there is no guaranty that the second interval code is starting @300.  What about a third interval code that should start @300? This one is not queued in. The event queue contains only one active/running interval code and one waiting.

 

So the event queue will not be flooded. Nevertheless try to avoid such situations, it can block UI event handling and other code parts.

Use Timers to Perform Non Blocking Operations

The first figure shows an event queue with a code block that takes some time. Imagine this code is doing some complex calculation and will take a while. During this time no other code can be executed (single thread), this means for example that the application user interface can not be responsive to users.

To break up a blocking code we can split it in different fragments and add some delay between their execution. This example demonstrate a split into 10 parts and uses a setTimeout of 20ms.

var fragments = 10;
var currentFragment = 0;

function doSomething()
{
   // Insert calculation here

   currentFragment++;
   if (currentFragment < fragments)
   {
      setTimeout(doSomething, 20);
   }
}

setTimeout(doSomething, 20);

This above example ensures that there is at least a 20ms time slot to execute other code like event handling.

Blocking versus Non Blocking

The figure shows us, how it can look like on the event queue. On the left side the blocking code and on the right side the fragmented version. And again be aware that the 20ms is not guaranteed and a longer mouse click event handling can change it.

Look at http://jsfiddle.net/tntg6/3/ for a full working demo calculating Fibonacci numbers.

To truly run code in background use  web workers, they are also able to utilize multi-core CPU’s and run code on another core. Web workers are only available for modern (HTML5) browsers.

Time and Timer Resolution

To complete the picture about time and timers in JavaScript we have to look at the accuracy. The accuracy is different between getting the time with Date() and using setTimeout(…) or setInterval(…).

Windows machines have a timer resolution of 10-15.6ms by default. Until recently, all browsers used the system timer, so they all were stuck to this resolution. On other OS, like OSX the system timer has a much higher resolution. Now a days, actual browsers have a much better resolution of 1ms. This just relates to the Date().

For timers actual browsers on desktop commonly using a 4ms resolution. But again it is not guaranteed. On older webkit browser you will get a 10ms resolution.

The resolution can change, depending on various circumstances. Some browser change the resolution for inactive tabs to 1000ms (Firefox, Chrome, …). Addionally chrome handles minimized tabs as inactive. The HTML5 specs leaves a lot of room for timer resolution and changing it during runtime. For more on this topic, read Nicolas C. Zakas great article about “Timer resolution in browsers”.

Recap

  • Code execution at specified time is not guaranteed
  • Single Thread JavaScript execution organized via event queue
  • Long code execution can block the user interface
  • Different time resolutions. (In general: 1ms for Date, 4ms for Timers, 1000ms for inactive)

References

[1] Supercharged JavaScript Graphic, Raffaele Cecco, O’Reilly, p. 38-45
[2] How JavaScript Timers Work, John Resig, http://ejohn.org/blog/how-javascript-timers-work/
[3] Timer resolution in browsers, Nicholas C. Zakas, http://www.nczonline.net/blog/2011/12/14/timer-resolution-in-browsers/
[4] Timers in HTML5, http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers 

Codebullets Restyled

Codebullets.com has a new fresh an modern design. After getting this done, we are strongly focused on new upcoming content….

Hope you like the new codebullets.

Hosting Services in Space

For the better part of last year I’ve been working on a new software with an interesting kind of architecture. It’s a distributed system designed to have high throughput, low latency as well as redundancies to achieve high availability. Additionally it is able to scale quite well from a very small system to a multitude of the original size.

A classic approach to build a distributed system is Service Oriented Architecture (SOA). The building blocks of such a system are several services talking to each other. Such a system usually uses a common communication layer like an Enterprise Service Bus (ESB) to make data and information exchange between service easier for the developer. But such an ESB is actually not a requirement to build a SOA application. Services which need information about certain data or events from another service subscribe for these data updates and store a local copy inside their own service for quick access (cache) in case the data is needed for custom logic.

This approach works very well for a lot of systems. The individual parts or features of an application are decoupled from each other, only sharing a specific data contract. This makes adapting and enhancing such a system easier. However, there arises a problem as more and more services are added. There is a lot of additional communication necessary to inform all subscribers of the data updates. This problem becomes much more pressing in a system where there is a high percentage of writes in comparison to reads. The next figure illustrates the problem.

Services broadcasting their data to every other service.

It shows a worst case scenario where every service subscribes for data of each other service. While it looks very simple with only 2 services, the number of possible communication paths and messages rises quickly as more and more participants are added. This is a big problem in larger distributed systems. The usual approach to tackle this is to design the services as independent as possible from each other. One has to design the services along the actual business cases. This reduces the communication effort quite a lot and at first it works really well. However as the system grows over time, features and additional data is added the problem surfaces again. Throughput and latency decreases as more and more messages have to be sent (probably in a secure manner) to other participants. The system scales only to a certain point until it no longer meets the throughput and latency requirements.

Unfortunately the system I am currently building has a lot of updates and very tight latency requirements. Therefore we reached the limits of SOA pretty fast. This is where something new comes in … Space Based Architecture (SBA). SBA takes ideas of SOA and grid computing and develops it further.

At the heart of the space is a distributed data cache (ex. memcache). It is used to spread the stored state across multiple hosts. It is also very fast as it does not involve any disc IO. To achieve redundancy the data is synchronously replicated to at least a second computer. In case of a software crash or hardware failure the data is still available on the backup instance.

SBA goes even further than just using an object data cache. Instead of just accessing the object cache from the outside the services and its logic become part of the cache. This results in multiple different services working on the same cache and  maybe even being hosted in the same computer process. Bear in mind that the services are still independent from each other. All they need to know for communication is a public contract very much like using SOA. The advantage is that instead of having to sent messages back and forth between service entities and probably different host computers,  those operations are just reads and writes to an in memory data cache on the same computer. In my last posts I’ve shown some of the necessary actions to achieve reliable messaging. Problems shown there do not necessarily apply here, we have communication on a single computer.

However, this needs to work as a cluster to achieve scalability. This means dividing the data into partitions across all services and computers in a way that data related to each other is stored in the same space partition. If this can be achieved we end up with multiple independent partitions containing instances of all our services logic.

Service collocated in one single space partition

Each partition handles a specific amount of work and to scale up we only have to supply more boxes being able to run additional space partitions. If a key can be found that evenly distributes our data and this key completely isolates our business uses cases we can achieve almost linear scalability. As the system grows over time we can just add additional computers to keep our latency and throughput requirements very low.

Unfortunately, in the real world such keys are hard to find. When taking something like an order intake number or zip code the data will probably not distribute evenly or the service logic may need data located in other partitions. This decreases the scalability a little bit, but as I have learned, it is still a lot better than other architectures I’ve come across so far.

Alternative Reliable Messaging

In my last post I talked about building reliable messaging with the help of a transaction coordinator and two phase commits. As can be seen this involves a lot of additional communication decreasing overall performance as well as throughput. This time I wan’t to talk about a cheaper alternative which is also reliable but much simpler to achieve.

Lets start with the error case described in my last post:

HTTP POST request is answered with HTTP OK. But OK response can not be delivered

A client sends a HTTP request to a server. The server itself performs one or more operations on a database and wants to report the result of the operation back to the caller. However, for whatever reason sending the response back to the client failed. As described, this results in a serious problem for the client. Last time the proposed solution was to use a two phase commit and a distributed transaction coordinator. This resulted in a lot of additional messages as well as necessary infrastructure to make it happen.

Another possibility is for the client to always send the request again, until a response is finally received. This may be problematic, depending on the message and the logic it triggers. The question here is whether the message/operation is idempotent. An operation is considered idempotent if the result of the operation is always the same regardless if executed once or multiple times. For example, if you set the name of a customer object the result is always the same. The name will have the new value regardless the number of times the request is executed. Things are lot different if the customer request creates a new order of pizza.

The trick to achieve reliable messaging without a two phase commit is to just keep on sending the request again and again. For this to work we have to make sure that all our messages and operations are idempotent. The problem here is that for each logic operation there are different ways to achieve this. There is no single way to do it. For example if the client places an order, a way to make it work is to check whether the customer has already placed one with the same number of articles in a recent time span. If this is the case, it is probably safe to assume the operation has already executed and needs not to be performed again. Depending on the message this criteria will probably change.

Do You see what is happening here? We exchanged the performance reducing infrastructure with additional development effort. Depending on the performance needed, this may be a reasonable trade off. If you have a little more control about the client/server as well as the messages we can even go one step further.

Lets try to push idempotency back to the infrastructure. For this we need a unique key assigned by the client to be generated and transported along with the message. The next figure shows the complete message flow.

Message execution logic is not executed again, after lookup of handled id.

Every time a message arrives, the server checks the ID and decides whether it has already been executed. After performing the logic it saves the ID in case the client wants to send the request again. If the client chooses to do so the sever performs a lookup and finds the ID marked as already executed. Therefore the server skips the execution step and sends the OK response directly.

One thing though, it is important that the logic operation and saving the executed message ID are only a single transaction. Otherwise it may come to an inconsistency on what has already successfully executed. When you have control of the database you can easily store the id with the very same database transaction.

The advantage of this approach is that you get the gains of message idempotency without having to burden your business execution logic.

The Road To Reliable Messaging

In this post I want to talk about how reliable messaging can be achieved. With reliable messaging I mean transporting the message safely from one service to another as well as executing the assigned logic in a safe way. This message handling should not corrupt any state and be consisted even in case of system and network failures.

First we have to choose a network protocol that ensures our messages are correctly transported over the network. Nowadays this is a real no-brainer, everyone is using TCP/IP for that, with a good reason.

As can be seen in the picture above every packet sent to the server is answered with a special ACK response. This indicates that the packet has been successfully received with all data intact. Additionally TCP implements features like automatic retry in case there is packet loss on the network, it ensures the correct packet order and so forth. No wonder it became a first choice when working on a widely distributed network like the Internet.

However, when used in a messaging system there is a little drawback. The ACK response does not carry any other information besides the successful transport indication. Unfortunately a great many times we need to return additional data back to client. The bare minimum is whether the unit of work as been executed successfully or not. This is not possible with a single TCP ACK representing only a successful message transport.

To overcome this problem often a protocol on top of TCP is used. One of the most famous request protocols in this regard is HTTP. The basic messaging pattern is shown below. The client sends a packet to server which has at least a HTTP header. If received successfully the packet is answered with the already known TCP ACK.

Next the server processes the request. This may result in reads or writes on a file system or a database. Once the server has finished processing the message a separate response is returned which contains a HTTP status code like 200 OK or 400 Bad Request. Together with this code additional data may be transported like a HTML, JSON or XML document. This pattern and processing is enough for a great many messaging applications out there.

Lets think about possible errors here and analyze whether this is reliable in case the network fails or a system crash. If the server crashes after successfully receiving the message, but before any work is done, no response will be sent back. The client will probably have some sort of timeout mechanism and can either wait or try again on the same or a different server. This is secure, we know the server has crashed and no harm is done, no state has changed. Now consider another scenario. The server receives the message, finishes a transaction on a data store and  at the next moment the problem occurs right before a success can be sent back to the client. In most cases this is not a problem either. For example if it was just a query and no state has changed on the server side, it will not corrupt anything. The client retries the operation and if it succeeds the second time around everything is fine.

The problem starts if the work done on the server involves write operations or sending messages to other services. Depending on the message and the operation certain side effects may occur. Consider something like drawing money from an ATM. If the operation succeeds on the server and the client is not informed about the success it may rightfully assume a failure and try again resulting in 2 transactions. As a result the money will be booked twice from the account while the ATM hands it out only once. This is bad, we need a solution for this. Continue reading

Ready for Digital Sketching with a Real Pen?

Wacom just released a new “real” and digital pen called “Inkling”. It works like a common ball-point pen on paper, but it also records and transfer your sketches to the computer.

Yesterday, I got my package with the Inkling and I started to play around. For the Inkling you don’t need any kind of special paper and it uses a standard ink refill.

Start Sketch Animation (if not started automatic)

The above simple sketch was created with the Inkling. The second chapter of this post shows how the animation effect was done with JavaScript.

How the Inkling works

To record a sketch the receiver unit has to be placed on the upper border of the paper. Then position and pressure (1024 levels) of your pen are saved to an internal 2GB memory. Your sketch is stored as a vector graphic, so the receiver can hold several hundrets sketches. I like the idea of using vector data. It’s just great to work with it directly in e.g.  Adobe Illustrator. Another great feature is drawing on separate layers. This means you can create a new layer with pressing a button on the receiver. Then every new drawn line is assigned to the new layer.

After your sketch is ready you can open it with the Sketch Manager and export it as PNG, JPG, PDF, SVG, BMP, TIFF or edit it directly in Adobe Photoshop or Illustrator (since CS3).  You can find out more about the Inkling here.

Wacom Inkling

Fazit

Very cool, I like it! Now, I am interested in how it will influence my daily work. After testing it two days, here is a list of pro and cons:

Pro:
++ Vector data
++ No special paper required
++ Standard ink refill.
++ Accurate position detection
+ Sketching on different layers
+ Lightweight pen for all the technical stuff inside.
+ Practical transport case with integrated recharger

Contra:
– Creating a new layer can sometimes result in an position offset between layers. Maybe I moved the receiver while pressing the new layer button. I will start to investigate this.
- Price (About €170 in Europe)
- You have to learn that nothing (for example: my non-sketching hand) shall be between the receiver and the peak of the pen.
- It is not possible to go back one layer

Missing:

The Sketch Manager has no OCR for text recognition. Using the Inkling for taking textual notes requires additional work steps and a separate OCR software.

Leave a comment and let me know how you like the Wacom Inkling? And now something for developers:

How to animate an Inkling SVG with JavaScript

To create this animation I am using the jQuery library. Download it and add it to your HTML document.

<script type="text/javascript" src="jquery-1.6.4.js"></script>

Then add the SVG image to the html document:

<div id="svgContainer" style="overflow: visible; width:500px; height:200px;">
   <embed id="svgImage" src="codebullets2.svg" onload="start()" type="image/svg+xml"
      style="overflow:hidden; width: 500px; height: 200px;" ></embed>
</div>

After loading the SVG image the animation shall start. The start function needs to get the DOM of the SVG. jQuery is not build for manipulating the SVG DOM, but since HTML and SVG are similiar to XML, a lot of operations are working. That makes the rest very simple. So this is the start function:

// Get the SVG DOM Document
var svg = $("#svgImage");
var doc = svg[0].getSVGDocument();

// Get all SVG g items.
_items = $($("g", doc));

// Hide all items
_items.hide();

// Show the SVG Image itself. But every SVG group is hidden.
// So at this point the user will see nothing.
$("#svgImage").show();

// Show the first SVG item
showSVGItem(0);

In the “hide” section you will find a jQuery selector for “g”. The SVG file of the Inkling Sketch Manager stores every single path/polygon data within a single group (g) element. So select all the groups, store them in a private var _items  and hide them. The showSVGItem function now displays a single “group” tag of the items list given by an index.

// Show an SVG item at given index.
function showSVGItem(index)
{
   if (index < _items.length)
   {
      $(_items[index]).show();

      // Show the next item with a delay
      index++;
      setTimeout(showSVGItem, _delay, index);
   }
}

That’s it, have fun. Please check the example HTML site with the complete source.

By the way the codebullets SVG file contains 1040 groups and the animation effect was tested with current browser versions of Opera, Safari, Firefox and Chrome.(IE9 has some problems.)

My Favorite Dependency Injection Container

As described in one of my previous posts the dependency inversion principle is one of the major design principles of software. It allows for easier testing as well as being much more responsive to requirement changes. Routing and wiring all these dependencies together is usually not performed manually by the developer. It is a very cumbersome task as one would have to take into account dependency chains as well circle dependencies and so forth. This is the task of a separate dependency injection (DI) container which is able to do all these things for us.

Injection by Andreas Levers - Licensed under CC

Until recently my favorite container has been StructureMap. It is very fast and has a great set of features. However it does not support all current .Net runtime scenarios. For example it will not run under the .Net 4.0 client profile or inside a Windows Phone 7 Silverlight app. For this reasons I searched around a bit and found Autofac to be a perfect replacement. Like with StructureMap it is very easy to set up with a fluent interface. Additionally it has features like automatic support for Lazy<T> types.

However, the most important feature for me to switch over to Autofac is a something called DelegateFactories. Sometimes there is an object which needs a parameter at runtime to be initiated. For example, think of a Queue class which needs a custom name as constructor parameter, or like in the example below a pseudo printer class having a text writer parameter where the text is printed to.

public class TextPrinter : IPrinter
{
  private readonly TextWriter _writer;

  public TextPrinter(TextWriter writer)
  {
    _writer = writer;
  }

  public void Print(string text)
  {
    _writer.WriteLine(text);
  }
}

With StructureMap I would usually solve this with a custom factory implementation. This factory would then be injected into any class which needs a reference to the specific printer. The factory itself is responsible for creating a new printer instance. Often this would mean for the factory to have a reference to the DI container itself to pass on the parameter. This is something I try to avoid if possible. My custom code should not depend on the infrastructure around it. Actually, using the dependency inversion principle it should be the other way round. The infrastructure should depend on my business code and try to fulfill its needs as best as possible.

Autofacs support for DelegateFactories solves this problem very nicely. Instead of injecting a custom factory it recognizes the structure of the delegate used as the parameter in my class constructor. In the example below I’m using a function which takes a TextWriter as parameter and returns an IPrinter instance as a result.

public class Invoice : IInvoice
{
  private readonly Func<TextWriter, IPrinter> _getPrinter;

  public Invoice(Func<TextWriter, IPrinter> getPrinter)
  {
    _getPrinter = getPrinter;
    this.Id = Guid.NewGuid().ToString();
  }

  public string Id { get; private set; }

  public void Print()
  {
    _getPrinter(Console.Out).Print("InvoiceId: " + this.Id);
  }
}

Have a look at the example code linked to this post. Please note that there is no code necessary to resolve this dependency to the factory delegate. Autofac automatically recognizes the delegate and creates the implementation code behind the scenes. All it takes as configuration is to tell Autofac the concrete implementations of IPrinter and IInvoice. This may be done in a custom Autofac module like this:

protected override void Load(ContainerBuilder builder)
{
  builder.RegisterType<Invoice>().AsImplementedInterfaces();
  builder.RegisterType<TextPrinter>().AsImplementedInterfaces();
}

The call parameter of the delegate is matched with the constructor parameter of the Printer class without any single line of additional code. As a bonus, it is not  necessary for the factory delegate to exactly match the constructors parameter layout. The printer may have additional dependencies not part of the the called delegate. As long as Autofac has a definition of them somewhere it will automatically fill in the gaps. This is really great and it makes my life working with the DI container so much easier.

Fighting Code Decay

Well, I guess all software developers have came across code which is considered to be ‘bad’. From my point of view code is bad if it has at least one of 3 characteristics. For me that is pretty much the opposite what Eric Lipperts defines in his article as good code.

  • Does not work according to the the functional requirements.
  • Is hard for the reader to understand.
  • Is very difficult to change as requirements are changing.

Most of the time I find this stuff in legacy code and of course not the one the team is currently working on. But then, how has this code been born into existence if no one ever wrote it? The answer is difficult and in my experience caused by a lot of different factors. When I talk to my fellow developers they tell me that the version of their piece of software is of course “perfect”. However, afterwards the problems start. Change requests from customers are coming in, errors are found, quick fixes are made, critical milestones are approaching way too fast and so forth. What happens now is, as Robert C. Martin (“Uncle Bob”) describes it, that the design starts to rot and decay. Given enough time the once so beautiful architecture is just a big pile of spaghetti code which is hard to maintain and costs huge amounts of money to keep in working condition as external environments are changing.

But how to avoid this? Is there a way to keep the code base clean, even if it is being worked on for a long time. In my experience this is a constant uphill battle.

An uphill battle - by Frank Kehren - licensed under CC

Keeping the code from decay takes constant effort. I often feel like going upwards endlessly with no end in sight.

Teams and companies often try to fight the starting chaos creeping into the code with rules and guidelines and maybe other quality gates like code reviews. However, the larger the code base gets the more effort it takes to enforce this. This results in increased costs in what originally seems to be just a little change or fix. The older the code gets, the more likely it is that the original senior developers have moved on to other projects and do not have the time to look over every commit and little feature added. Maybe they are not even working in the company at all. As a result the code starts to decay and we are back at square one.

The only thing which really seems to help in this fight is to automate the quality measurements available as much as possible. It is also important to try to detect violations as early as possible. I often heard the sentence: “I’m going to fix this later.”. Chances are good it will never be changed at all. The only way to really enforce coding rules is, if the compiler generates an error as the violation occurs. This is the only way to force a developer to do it as it was originally intended.

I’m primarily working with .Net and C# and in my opinion there are some good tools around to help with this. This ensures a continued quality of the code even for longer projects and projects which have long switched from development into maintenance mode.

The first one is StyleCop. This is a static code analysis tool originally developed by Microsoft but has been made available as open source later on. It can easily be integrated into the Visual Studio build process. It already ships with a lot of reasonable rules and I’ve implemented even more. For example in our team we have rules limiting the maximum allowed cyclomatic complexity and maximum effective lines of code per method. Additionally there is a rule to limit the total number of lines per file. This alone provides a very effective protection against god classes and methods.

Another one is FxCop which is available in Visual Studio Professional (and greater) under the code analysis project options. This one checks more advanced patterns like correct disposing of objects and other probable mistakes.

Probably the most important tool is NUnit or any other unit testing framework. For me, it currently seems the only way to ensure that existing features still work after code has been changed. In comparison to a full system regression test it is also very cheap and pays off very quickly.

Well, I guess these are the most important ones coming to my mind. Of course there are other tools available like for example NDepend to continuously check your architecture. However, in my opinion if you have the ones mentioned above in place together with a separate  build server you are very much on the right track.

Here’s a Quick Way to Get All the CSS Colors

A bad part of CSS is that it has no support for variables or placeholders. So we can not define a color value somewhere,  to use it easily with different styles. Every style using a color has to define a concrete color value in the format of #rrggbb or rgb(0-255,0-2555,0-255).

An example:

h1 { color: #0000F1; }
div { border-color: #0000F1; }
span.highlight { background-color: rgb(0, 0, 241); }

This example uses the same color for all elements. If you have worked on a bigger web project then you know what can happen:

  • CSS files tend to grow and there is always more than one css style file.
  • Colors tend to be changed more often than the designer likes it.

Color Scheme JavaScript

To discover what color values a website really uses, I wrote a short JavaScript Code that analyses the used css styling and shows a color palette. This chapter explains how the code works, skip this chapter to go directly to “How To Use colorScheme.js”

The script uses the jQuery library to get css values of an element. It is really easy to get the background color, for example an element with id = “MyId”. The $ sign stands for jQuery.


var color = $("#MyId").css("backgroundColor");

Visit jQuery site to learn more about jQuery.

The colorScheme.js module has two important functions:

  • analyse – recursive function that analyses all child elements for colors, starting with the <body> tag.
  • create – creates the color palette within the element specified by its Id.

The analyse method is automatically called when the html document is loaded and ready.

   // Stores the colors
   this.colors = [];
   
   var that = this;

   $(document).ready(function ()
   {
      that.analyse();
      that.create("colorPalette");
   });

The analyse method uses the getAllColorsRecursive method with $(“body”) as argument. It stores the backgroundColor, color, borderColor of all elements in the colors object.

   function getAllColorsRecursive(jqObj)
   {
      addColorFromCss(jqObj, "backgroundColor");
      addColorFromCss(jqObj, "color");
      addColorFromCss(jqObj, "borderColor");

      // Analyse all children.
      jqObj.children().each(function ()
      {
         getAllColorsRecursive($(this));
      });
   }

The create method adds an item for each color to the given colorPalette element. The color item structure looks like this:

#????? will be replaced with the specific color value. Now you can style your own color palette, or use the styling from the example at the end of this post. ;-)

How To Use colorScheme.js

Download the colorScheme.js script file.
The script uses the jQuery library, can be download at http://jquery.com/.

Add the scripts to your page with:

<script src="jquery-1.5.js" type="text/javascript"></script>
<script src="colorScheme.js" type="text/javascript"></script>

Add a div element with id=”colorPalette” to define a place where the color palette shall be shown.

<div id="colorPalette" ></div>

The script will generate the color palette automatically when the html document is loaded and ready.

Add some styling for colorItem, colorItemColor, colorItemText to get a pretty color palette or use this to get the following look:

Script used on this page.

This is the color palette of codebullets.com

There Is a Time for Unit Tests

I’ve come accross a nice post from Mike Hadlow called I Don’t Have Time for Unit Tests. Backed up with data from the Microsoft Visual Studio team, he concludes that doing TDD and unit tests is one of the things actually helping developers spending time on real coding. If no unit tests are in place developers spend most of their time trying to understand existing code and fixing bugs which should not have been there in the first place. As he describes most of the productivity gains using TDD come from:

  • Allows safe modifications. If you break something when you modify some code, the unit tests fail.
  • Shortening the iteration cycle between writing/running code. No more need to step through your application to part where your new code gets exercised.
  • Mistakes in your code are shallow and obvious. No more need to step through code in the debugger, wondering which part of your application is broken.
  • Code is self-documenting. The unit tests explicitly show how the author expected the code to be used.
  • Code is decoupled. You can’t do TDD without decoupling. This alone makes the code easier to understand as a unit and much safer to modify.

I do agree completely on these points. It matches with my own experience doing TDD. However, recently I find myself doing some coding without any tests in place. Why is that? After all I’m a big fan of TDD and high quality code. Shouldn’t I do unit tests under any circumstances, no matter what?

Well, I found that there a are some (minor) cases where TDD does actually get in the way. One of those cases are Proof of Concepts (POC) where I try to learn something completely new to me, or figure out if an idea could actually work at all. The important part here is that these POC are rather small in effort (<40h) and are not used directly in real production code. Once the POC is finished I take the lessons learned and start anew. The second time around you are going to make things even better,  put it into production and have proper tests in place right from the start.

Another area where I’m bad with unit tests are internal tools like test clients for our services and other such little helpers. The important thing here is that they are very small (<40h) and are typically used only by myself or a very limited number of people. Again it is not production code we are talking about here. Sometimes it happens that such a tool or test client begins being used by more people as it satisfies a demand by other fellow developers, engineers or admins. If this happens it is better to trash the old tool and make something new and probably even better. After all, not much effort went into creating it in the first place and chances are good that I am even faster and and can improve the existing design the second time around. But this time I do it with all proper tests and QA tools in place.