22 June 2015

Timeouts and TimeSpans

Huh? We’re waiting how long?


You don't have to work for a long time in software development to come across code similar to the following

void DoSomething()
{
   var data = GetData(5000);
}
Data GetData(int timeout)
{
   Thread.Sleep(timeout); // or something that takes a while
}

There is one major issue with this code that specifically relates to its readability and consequently its long term maintainability.

Can you spot it?

Don’t worry if you couldn’t. This is a very easy flaw to miss and is usually not uncovered until someone is tasked with maintaining or changing a block of code like this.

What is a “timeout”

The issue with the code block above is that the unit of the “timeout” value is unclear at the point of use.

5000 of what? Seconds, micro-, milli-, nano-, cpu ticks? *gasp* maybe it’s minutes! You just can’t be sure unless you check.

This one coding issue has in the past caused me to loose countless minutes in extreme code deep-diving and wading through disassembled code just to figure out exactly what unit is being implied for “timeout”.

Issues such as these can also cause more subtle and hard to track down issues related to unit mismatches as the code is extended or used by other programmers. What if one programmer is expecting milliseconds but others supply microseconds? Sometimes these issues cause multi-million dollar losses as was the case with the Mars Climate Orbiter in 1999.

For every problem there is a solution

Here are three simple alternatives that can help you avoid making or mitigate this kind of an issue and significantly improve your and your colleagues life’s in the long run.
The code examples below are presented in C# but apply to most modern programming languages.

Solution 1: Working under tight constraints

By simply tagging the relative function and parameter names with the explicit timeout unit a lot of uncertainty has been removed. If changing the function name is impossible due to legacy constraints, just changing the parameter name to reflect the unit will help immensely and can usually be done without sacrificing any backwards compatibility (exceptions to this are when relying on named parameters).

void CoolAndClear()
{
   var data = GetDataWithTimeoutMSec(5000);
}

Data GetDataWithTimeoutMSec(int timeoutInMilliseconds)
{
   Thread.Sleep(timeoutInMilliseconds);
}

Solution 2: Having full freedom to change

The absolute best case scenario is when you’re able to modify the parameter type to be a non-ambiguous type. An example of this would be to change the timeout variable’s type from int to a System.TimeSpan struct instead.

void CoolAndClear()
{
   var data = GetData(TimeSpan.FromMilliSeconds(5000));
}

Data GetData(TimeSpan timeout)
{
   Thread.Sleep(timeout);
}


In this case the exact unit is explicitly stated at the point of use and all ambiguity is removed. This also provides solutions for special cases such as when specifying an Infinite timeout value or special hard-coded custom values.

Note that it would not be advisable to mix both Solutions 1 and 2. Their combination would introduce even more ambiguity than before. Such as this statement

GetDataWithTimeoutMsec( TimeSpan.FromMinutes(10) )

Solution 2: Extra credit

When using the System.TimeSpan or other custom object there exists the possibility in C# to create extension methods to make the code even more concise and simpler to read

void CoolAndClear()
{
   var data = GetData(5000.MilliSeconds());
   // or
   var data = GetData(20.Seconds());
   // or
   var data = GetData(3.Minutes());
}

If you like this approach then feel free to download the skeleton code for these extension methods from my OneDrive.

Solution 3: Working under impossible constraints

In some cases you might find yourself working under almost impossible constraints where modifying any part of the code is not permitted. In those cases adding clear documentation would still be a huge improvement.

void CoolStuff()
{
   var data = GetData(5000);
}

/// <summary>
/// Gets data with a user supplied
/// <see cref=”timeout”/> in milliseconds.
/// </summary>
/// <param name=”timeout”>The timeout value in milliseconds. 
/// Value of 0 will cause the function to return immediately. 
/// Value of -1 will specify an infinite waiting period.</param>
Data GetData(int timeout)
{
   Thread.Sleep(timeout); // or something that takes a while
}

Actually come to think of it, even if you end up choosing to do either solution 1 or 2, always do Solution 3 as well.

.     .     .

This entry can also be found on Medium:
https://medium.com/@sverrirs/timeouts-and-timespans-ca05ae5c2d15#.usxppi1h8

[Arhived] Timeouts and TimeSpans: Huh? We're waiting how long?

Update 4 Feb 2016 There is a more up to date version of this article here

You don't have to work for a long time in software development to come across code similar to the following:

void DoSomething()
{
   var data = GetDataWithTimeout(5000);
   //... continued
}
Data GetDataWithTimeout(int timeout)
{
   //...
   Thread.Sleep(timeout);
   //...
}

There is one major issue with this code that specifically relates to its readability and consequently its long term maintainability:

  1. The unit of the timeout value is unclear at the point of use!

This has caused me to loose countless minutes to drilling to extreme depths to figure out exactly what unit is being implied on the timeout.

How to avoid this loss of productivity and immediate code rot?

Here are two simple alternatives that can help you avoid making this kind of a mistake and significantly improve your and your colleagues life's in the long run.

1. Explicitly mentioning the timeout unit

By simply tagging the relative function and parameter names with the unit a lot of uncertainty has been removed. If changing the function name is impossible due to legacy constraints, just changing the parameter name will help immensely and can usually be done without sacrificing any backwards compatibility.

void DoSomething()
{
   var data = GetDataWithTimeoutMSec(5000);
   //... continued
}
Data GetDataWithTimeoutMSec(int timeoutInMilliseconds)
{
   //...
   Thread.Sleep(timeoutInMilliseconds);
   //...
}


2. Relying on TimeSpan and helpful extension methods

In the case where you're able to modify the parameter type no renaming is necessary as the code can be modified to use the System.TimeSpan struct instead. Actually I would advise against also using the renaming tactic if this approach is used as combining them will introduce more ambiguity than before (calling GetDataWithTimeoutMsec(TimeSpan.FromMinutes(10)) would be confusing.

void DoSomething()
{
   var data = GetDataWithTimeout(5000.MilliSeconds());
   //... continued

   // Other examples
   var data = GetDataWithTimeout(20.Seconds());
   var data = GetDataWithTimeout(3.Minutes());
}
Data GetDataWithTimeout(TimeSpan timeout)
{
   //...
   Thread.Sleep(timeout);
   //...
}

The skeleton code for the Seconds()/Minutes() extension methods can be downloaded from my OneDrive here.

This entry is also available on LinkedIn:
https://www.linkedin.com/pulse/timeouts-c-timespans-huh-were-waiting-how-long-sverrir-sigmundarson

2 Feb 2016 An updated version of this entry can now be found on Medium:
https://medium.com/@sverrirs/timeouts-and-timespans-ca05ae5c2d15#.usxppi1h8

16 June 2015

Upgrading the UI for the Météo weather forecast site (#2)

After building the initial version of the Météo weather page and confirming that the data was all correctly handled I went about sprucing the UI up a bit.

Try it

This project has been updated, click here for part three (data enhancements) of this article.

Not only was the original design purely a functional one and not particularly attractive or user friendly but it was also missing a few key data points such as intra-day weather and likelihood of rain.

The Old UI

The tools

With the help of JQuery and the JQuery UI I managed to wrestle it into a usable and aesthetically pleasing look and feel.

I ended up using the JQuery Accordion without too much customization. This widget suits the website quite well as I wanted to be able to show an overview of the next 10 days at a glance but then allow the user to drill down into each day to see the intra-day forecast in more detail.

The final UI design

The accordion is closed upon first loading the website but then the user can tap each day to drill down and see more detail data.
The initial view of the website
Accordion is closed

User has expanded a day and intra-day forecast is visible
Accordion is open

For longer term forecasts additional information is available on how confident the Météo weather model is about the prediction as well as a rough prediction of the likelihood of precipitation.
Extra data points are available for days further into the future

Customizing the forecast area

A new addition was the setup screen. This screen can be used to change the forecast area to a different city or area. This page is available by either clicking the name of the current area at the top of the page or scrolling all the way to the bottom of the page and clicking the "Configure" link.

Try it

The Setup Screen
The user can type into one of the three textboxes

Suggestions are offered as the user types.
Both place names and zip code entries are supported



Feel free to try this forecasting site out and even bookmark it for future use

Try it


This article is also available on LinkedIn
https://www.linkedin.com/pulse/ui-upgrade-météo-mobile-weather-forecast-site-sverrir-sigmundarson

1 June 2015

Getting hassle free and fast(er) weather forecasts in France (#1)

The Météo-France Android app has been annoying me for the past 6 months with its excessive battery usage and frustrating UI navigation and experience. Finally this week I had enough and decided to come up with something simple that still gives me the same information on my mobile as the rather excellent France Meteorological office prepares and publishes.

Try it

This project has been updated, click here for part two (that discusses the UI redesign) and part three (data enhancements) of this article.

Design

As the French Météo does not publish any of its data in an easily programmable way I decided to do simple screen scraping of their existing forecast website. This is straight-forward enough to do in PHP and actually made considerably easier using the SimpleHTMLDOM library. I highly recommend it. It is the closest I've come to having BeautifulSoup in PHP.

The service is split into two pages: 

API

Scapes and re-renders the Météo data into either a JSON or JSONP format.

Try it

Supports the following URL parameters:
ParameterDescription
&area=Lowercase name of the region or area you're interested in. E.g. strasbourg, eckbolsheim
 
or saverne. Defaults to "strasbourg"
&zip=The zip code for the area. This should correspond to a zip code available in the area used. Defaults to "67000"
&callback=Optional, if used then the call becomes a JSONP response and this value will hold the name of the client side Javascript function that should be called when the call returns.


Relies on support data from the following resources:
http://labs.coruscantconsulting.co.uk/strasbourg/meteo/img/spriteCarte40Uvs.png
http://labs.coruscantconsulting.co.uk/strasbourg/meteo/img/spriteCarte40Temps.png
http://labs.coruscantconsulting.co.uk/strasbourg/meteo/legend.css

Website presentation

Simple HTML/Javascript front on top of the forementioned API functionality. Supports both AREA and ZIP parameters described above.

Try it

Examples

Default call in HTML format:
http://labs.coruscantconsulting.co.uk/strasbourg/meteo/index.php

Eckbolsheim weather info in HTML format:
http://labs.coruscantconsulting.co.uk/strasbourg/meteo/index.php?area=eckbolsheim&zip=67201

Saverne API response:
http://labs.coruscantconsulting.co.uk/strasbourg/meteo/api.php?area=saverne&zip=67700

Default API response with JSONP callback:
http://labs.coruscantconsulting.co.uk/strasbourg/meteo/api.php?callback=weatherdatafunction



This acticle is also available on LinkedIn:
https://www.linkedin.com/pulse/getting-hassle-free-faster-weather-forecasts-france-sigmundarson