Nothing Is So Simple That it Cannot Be Difficult

Long years in the software industry have conditioned me to dread last-minute feature additions. Something as innocuous as a mailer subscription form can turn into a minefield of security and privacy concerns if done incorrectly. In the book Peopleware, writers Tom DeMarco and Timothy Lister have expressed how managing software projects is less of a technical challenge and more of a social interaction maze. Keeping clients happy while still being able to convince them about the intensive behind-the-scenes work behind the simplest of features takes a lot of people-skill.

Incomplete or inaccurate specifications can complicate the problem even further. This can be a result of the specifications being created by inexperienced people, or people with little or no understanding of UX or software. This becomes particularly insidious because the presence of a specification (even if it is only superficial) lulls stakeholders into thinking that the project is under control. But all sorts of bad things begin to happen once the rubber meets the road. Designers work towards an incomplete layout. Engineers make an incomplete product, which results either in customer dissatisfaction or time and cost overruns.

A seemingly simple feature such as pagination requires quite a bit of programming just to make it work at all. More code has to be written to consider common cases such as representation of and navigation through large data sets. Usability issues have to be taken into account, such as device specifics to handle different input systems such as touch screens, keyboards and mouse clicks.

Product requirements often begin with a very vague idea of what is required. “A blog application needs comments”, says the product manager. So the engineering team gets to work and churns out a comment form, and a display mechanism. But nobody expected Jeff Atwood to deploy the software on his website, which regularly gets 3000 comments in the first 10 minutes of a post being put up, and nobody can now open his website any more because the database server choked on retrieving so many comments for a million simultaneous visitors (yes, even if they are flat discussions).

After Jeff posts a rant on his website, the product manager eats his hat and gets back to writing a specification for the comment pagination, as he should have to begin with. This is his design from the first draft of the specification.

Previous | 1 | 2 | 3 | 4 | 5 | Next

The engineering lead looks at the design and notices that it is still incomplete. The Previous and Next buttons will not do anything useful if the visitor is already on the first or last page. So those links will have to be disabled as necessary. The revised design looks like this.

Previous1 | 2 | 3 | 4 | 5 | Next
Previous | 1 | 2 | 3 | 4 | 5 | Next

But what happens when there are more than 5 pages of comments on the post? If they keep increasing the page count, eventually it will have to be wrapped to the next line or made to run off the screen, either of which looks very ugly.

Previous1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Next

Somebody suggests letting users type in the page number in a text field that also doubles up as the current page indicator.

First |  | Last

While this is easy, it is not very user friendly. How many pages of comments do we have in all? What happens if the visitor enters too large a number or a non-numeric value? Visitors on mobile devices probably will not be very pleased to have to type very frequently.

After yet another round of discussion, the team finally decides that visitors are probably not interested in viewing every comment on the blog. Yet, showing the total number of comments would be desirable for Jeff because it is a measure of his popularity. Fitness models measure bicep circumference. Geeks measure blog comments.

Somebody suggests the following user interface, which seems to fit the bill.

1 | 2 | 3 | 4 | 5 ... 274
1 ... 65 | 66 | 67 | 68 ... 274
1 ... 270 | 271 | 272 | 273 | 274

The first and last page links are always displayed. The rest of the links are dedicated to displaying the current page number and a range of values around it. For the end user – the website visitor – the control is very simple and easy to learn at a glance.

Of course, this entire exercise is moot if it is done without proper usability testing with relevant target audiences in mind. Formal testing methods are often inaccessible to small teams, but hallway tests can still provide feedback, and results in a much better product.

A Binary Clock using C#

Bit manipulations are second nature to electronics engineers, embedded programmers and a swathe of engineers who work with low-level systems software such as operating systems, languages and critical frameworks. While it does seem daunting at first, the fundamentals are very simple as explained in my previous post. This post builds upon those concepts to implement a simple binary clock using C#.

The core of the clock is in the BinaryClock class that inherits PictureBox, since this is primarily a visual control and needs a visual context to display its output. Inheriting from PictureBox also makes it easy to use as a drag-and-drop control in the Visual Studio IDE.

BinaryClock consolidates the timekeeping and drawing capabilities into a single class (the OO design crowd may cringe now). An instance of the Timer class ticks every second to invalidate the display and trigger a refresh. The mode field determines the method used to display the clock face – pure binary or binary-coded decimals. Its value can be set from one of the values in the imaginatively-named enum in the same class called Modes.

This brings us to the paint method which is triggered whenever the control has to be redrawn.

void Paint(object sender, PaintEventArgs e)
{
    DateTime dt;
    int h;
    int m;
    int s;
    Rectangle area;
    int offsetX;
    int offsetY;

    dt = DateTime.Now;
    h = dt.Hour;
    m = dt.Minute;
    s = dt.Second;

    area = new Rectangle(0, this.Height - BinaryClock.RECT_SIZE, BinaryClock.RECT_SIZE, BinaryClock.RECT_SIZE);
    offsetX = this._columns * (BinaryClock.RECT_SIZE + BinaryClock.RECT_OFFSET);
    offsetY = BinaryClock.COL_OFFSET;

    // Get bits for the hours component
    this._draw(h, e.Graphics, ref area);
    area.Offset(offsetX, offsetY);

    // Get bits for the minutes component
    this._draw(m, e.Graphics, ref area);
    area.Offset(offsetX, offsetY);

    // Get bits for the seconds component
    this._draw(s, e.Graphics, ref area);
}

This method begins by fetching the current time and extracting its components. Offset values required for the drawing are also initialized depending upon the current display mode. It then makes three calls to the drawing method to draw the appropriate graphics for the hour, minute and second values. Two draw methods are implemented in this class – drawBinary and drawBCD. Both take three parameters – the value to be represented, the Graphics object, and initial position.

Binary Drawing

The drawBinary method draws 6 boxes, vertically stacked, in a single column to represent the value in pure binary.

The application running in pure binary mode
for (i = 0; i < 6; i++)
{
    bit = value & (1 << i);

    if (0 == bit)
        g.FillRectangle(_offBrush, area);
    else
        g.FillRectangle(_onBrush, area);

    area.Offset(0, - (BinaryClock.RECT_SIZE + BinaryClock.RECT_OFFSET));
}

The value of each bit in a single number is extracted through the following snippet.

bit = value & (1 << i);

This is an application of testing if the n-th bit is set in a number. The digit 1 (0b00000001) is left-shifted to the position at which the bit in the value is to be inspected, then ANDed with the value.

0b00001010 & 0b00000001 = 0b00000000
0b00001010 & 0b00000010 = 0b00000010
0b00001010 & 0b00000100 = 0b00000000
0b00001010 & 0b00001000 = 0b00001000

The bit has been set if the result is greater than 0.

This is applied in a continuous loop through all the bits in the number. The colour of the box is determined by the value of the bit in that position. Zero is filled with the off colour, and any other value is filled with the on colour.

Binary-coded Decimal

The second function – drawBCD – has the same signature as drawBinary. The only difference is in the way it represents the number on the canvas. Instead of drawing the component value in a single column, it splits it into two decimal digits and draws each digit in its own column. The individual digits are extracted by dividing and modding with 10, then calling the drawBinary function for each digit.

The application running in BCD mode

The Visual Studio solution for this project can be downloaded from here as a ZIP archive.

Reading Time on a Binary Clock

Binary clocks are probably one of the epitomes of geek cred. Everybody can read an analog or digital clock that represents numbers in base 10. But it takes a geek to read the time from a gadget that uses an obscure and cryptic number system. Call it the hipsterdom of technology.

Understanding Number Systems

Modern number systems are remarkably similar to each other conceptually. The only difference is their applicability in different scenarios. The decimal system is in common use every day all over the world. Many fundamental concepts that are carried forward into other systems were refined using base 10 numerals. The most essential of these are naming unique digits, and positional notation.

Unique Digits

Numbers are a strange beast in that they have no end. The most primitive counting systems used scratches in the dust or pebbles to keep count. It became easier to represent larger values with the advent of separate symbols to identify different numbers. Roman numerals had special symbols for many numbers such as 5 (V), 10 (X) and 50 (L). While this made representation of larger values more compact, it still wasn’t perfect. It took the Indians, and later the Arabs, to finally come up with an extensible, yet concise number system that could represent any imaginable value.

Since it is impossible to have unique representations for every number when they are essentially infinite, the Hindu-Arabic numeral system instead has 10 unique symbols in base 10 to represent the digits from 0 to 9. By applying positional notation, all possible numerals can be represented by using these 10 symbols. Numbers greater than 9 are represented by stringing digits together. The leftmost digit has a greater magnitude than the one to its right, and the value of the numeral is a sum of its digits multiplied by their magnitudes.

Positional Notation

The magnitude itself is a power of the base. In the decimal system, the base is 10. Hence, the magnitude is 10 raised to a power that increases by one for every leftward shift. The rightmost number is multiplied by the 0th power of 10 and represents the ones position. The position to its immediate left is multiplied by 10 raised to 1, the next by 10 raised to 2, and so on.

Let us take the numeral 256 to illustrate this.

256 = 2 × 10² + 5 × 10¹ + 6 × 10⁰
    = 2 × 100 + 5 × 10 + 6 × 1
    = 200 + 50 + 6
    = 256

Binary uses the same concept to represent values. The only difference is that the rollover value in binary is 1 since it has only two digits – 0 and 1, and the number is multiplied by a power of 2 instead of a power of 10. It is also more verbose than the decimal number system. Even a relatively small value like 25 requires 5 digits in binary – 11001.

11001 = 1 × 2⁴ + 1 × 2³ + 0 × 2² + 0 × 2¹ + 1 × 2⁰
      = 1 × 16 + 1 × 8 + 0 × 4 + 0 × 2 + 1 × 1
      = 16 + 8 + 0 + 0 + 1
      = 25

In this sense, number systems are identical to odometers. When the rightmost digit reaches a certain maximum value, it goes down back to zero and the digit to its immediate left increases by one. If the second column is also at the largest digit, then it too resets to zero and the increment is applied to the third column.

Being able to read binary representations is obviously an essential requirement to read the time in a binary clock.

Structure of a Binary Clock Face

There are two types of binary clocks possible – ones that use binary coded decimals, and true binary clocks.

A clock face that uses binary-coded decimal notation

A BCD clock face is divided into six columns – two for each component of the time. Each column contains up to four rows, one for each power of two. The leftmost two columns represent the hour, the middle two are minute columns and the last two represent seconds. Each column represents a single base 10 digit of time. For example, if the value of column one is 1 and that of column 2 is 0, then the clock is representing the 10th hour of the day, or after 10 am. Similarly, if the value in column three and four is 3 and 2 respectively, the clock is in the 32nd minute of the current hour.

A clock face that represents time components in pure binary notation

True binary clocks represent each time component in a single column. Such clocks require only three columns, and up to six rows in each column to adequately cover all required values. Each column represents the absolute value of the component in binary encoding. For example, 0b001010 in the hour column represents 10 (1 × 2³ + 1 × 2¹). 0b100000 in the minutes column represents the 32nd minute of the hour. Together, the two values indicate the time as 10:32 am.

Even if you are not very accomplished at converting from binary to decimal easily, there are only a few values required to display the time in binary. Most people can easily memorize the light sequences and the values they represent after a few days of practicing.

Introducing Amaretto

It is daunting to straddle a flimsy contraption of metal tubes and ride in the midst of two-ton behemoths. Without electric horns or 50-watt headlights, you’re left to fume in silent, invisible panic every time a moron behind a wheel swerves into your lane without warning or reason.

Leaning down, hunched over and gripping a threadbare strip of cloth around the bars as cushion isn’t exactly the lap of luxury. Your backside, spoiled over a lifetime of sitting astride soft surfaces, hurts from the hard saddle. Road surface contours become more pronounced. Whereas a twist of the throttle on a motorcycle barrels up the steepest of climbs with nary a sweat broken, your legs now scream for mercy at every upward incline. And you touch a breathtaking top speed of 40 kilometres per hour for a total of 30 seconds before your lungs collapse in sheer exhaustion. The slightest headwind multiplies your suffering by orders of magnitude, and the elusive tailwind never seems to appear. Let’s not even talk about the inevitable, sweet suffering of DOMS the following day.

The cold wind bites hard, and sharp sun stings deep. But you wear the sun-tan with pride, even when it polarises your limbs, leaving you looking like a Frankensteinesque freak of mixed dark and light human componentry.

Amaretto is a sweet, almond-flavoured, Italian liqueur. It is made from a base of apricot pits or almonds, sometimes both.

And yet you soldier on, all discomfort forgotten behind the stupidest grin on your face as you slice through empty streets on a Sunday morning ride. Because inside every motorcyclist there is a little boy who just wants to ride a bicycle all day.

Say hello, fellow riders, to Amaretto.

Programming Beyond 9 to 5

In my previous post, I elaborated on the importance of reading for software developers. Keeping up with new advances in technology demands that its users have a healthy appetite for the written word. However, reading is just part of the equation for engineers. Knowledge gleaned through books offers no benefit unless it can be applied efficiently in their daily work. And quality programming, like every other art form, requires continuous practice.

A person who is uninterested in programming beyond its ability to help bring in a monthly paycheck, would typically not want to spend any more time than absolutely necessary in performing this activity. I don’t always hold side projects very high up in the evaluation matrix, but it is a pretty good indicator about the candidate’s interest in programming beyond the mundane stuff. After all, most programmers only get paid to write business software. If they want to write their own stack implementation that already ships as part of their framework, their employers will not be pleased to have them attempting to roll their own. Not only will it be a very inefficient use of time, but hand-rolled implementations are going to be nowhere as performant and bug-free as the libraries that ship with mass-consumed frameworks.

However, side projects do not come under strong timeline or performance pressures, nor are there constraints about the runtime environment or language choices. Who is to object if an individual feels inspired enough to write a stack in Brainfuck?

Educators have long since accepted the importance of learning by doing, especially for scientific topics. There is only so much one can absorb about the stack data structure by reading about it. At some point, one must put down the book and let the rubber meet the road, so to speak. Side projects in languages or frameworks other than what is used at work is a great way to learn new stuff. And it is a natural progression to reading about something new. Writing one’s own implementation of the Towers of Hanoi game cements whatever knowledge the book provides about the data structure. And depending upon the type of project we are talking about, individuals can easily play their best card. Those who are visually-gifted or otherwise have access to a collection of high quality graphics, a finely polished interactive utility or game can make a great impression. Those with a less-than-perfect eye for graphic design, a programming API with accompanying documentation can make an equally compelling case for their skills.

Again, there are many avenues for programmers who want ideas on programming projects. All that is required is the will and tenacity (not to mention the skill itself to begin with) to come up with a project idea and take it through to completion.