Small Scale Disaster Recovery Planning

Reading Time: 2 minutes

Or why to but a top efficiency freezer.

Fridge
An A Rated Fridge-Freezer

So the power company decided to schedule a 9 hour outage for today and not bother telling us. At 09:15 the power went off and we were suddenly in the dark. No power, no network and even the cordless house phone was off. Sure we have mobiles but we live in a dip and have minimal signal.

We’re screwed, right?

Not at all, because when I became a remote worker I spent some time working out exactly what I’d do if this happened. Dress this up in fancy clothes and a consultant will call it “disaster recovery planning” and relieve you of the contents of your wallet. The reality is that it’s just a bit of common sense, but it is important that any small business actually does it.

There’s an old phone I keep in the spare bedroom that doesn’t need external power so within a couple of minutes we have some form of communication. All the utility company phone numbers are on a board by the fridge so within 10 minutes I want someone’s head on a plate. At least I know the score though and it means we’re out of the office for the day. We both use (docked) laptops as our primary machines so we grab them, an external HDD and a bunch of other goodies and decamp to a nearby relative’s. All sorted.

If you are a small business, a remote / home worker or a contractor you need to think about what you’d do if something goes wrong. There are four things to look at.

  • What can go wrong?
  • How likely is it?
  • How severe it it?
  • What are you going to do about it?

There are 2 parts to the last one. One part is obvious, what you do when it happens but you should also consider how you can mitigate it – how you can make it less likely or its effect less serious if it does happen.

Oh, and a small piece of advice, always get the most efficient freezer you can. 9 hours of no power and not a hint of defrosting!

No Mr Bond, I Expect You To Die!

Reading Time: 5 minutes

or C#’s Short-Circuit and Left-To-Right Evaluation

I’m bad! I’m bad! I’m so bad I should be in detention!

It’s all Rob Miles’ fault. Just before Friday lunch time he unleashed upon the world a work of unspeakable evil. There’s nothing wrong with the text of the article – Rob is his usual erudite self – rather that HDR-like picture of the Gulbenkian building. It nearly melted my face off.

It being Friday lunch time I thought I’d retaliate, not with more impossibly bright HDR photography but by doing unmentionable things to Anders Hejlsberg‘s wonderful language C#.

The challenge is this – the following is a reasonable enough piece of code but…


if (filmChoice == 1 && age >= 15)
    Console.WriteLine("Enjoy the film");

When you’re just learning to program it’s easy to make mistakes…


if (filmChoice == 1 && age >= 15)
    Console.WriteLine("Enjoy the film");
else
    Console.WriteLine("Access denied - you are too young");

There are 3 combinations of filmChoice and age that will lead you down the else path, not just when the customer is too young to see film 1.

So you need to break up the condition… or do you? Could you actually do it with just 1 if statement? Oh yes.


string film = "the other film", message = ", but you could see looper";
if ((filmChoice == 1 && (film = "Looper") != null && (message = "") == null)
  || age < 15 && ((message = "") != null)
  && filmChoice == 1)
    Console.WriteLine("Access denied to " + film);
else
    Console.WriteLine("Enjoy " + film + message);

I'm actually practising my evil laugh right now. Later I will be uttering phrases like "No Mr Bond, I expect you to die!" and leaving the room allowing one of your dashing heroes to perform an improbable escape and ultimately foil my dastardly plan for world domination.

Seriously though, that code has been totally marinated in wrong sauce. Do anything like that in production code and your head will be on a spike in traitor's cloister faster than you can blink. Nevertheless it actually reveals some interesting and useful language features.

  • C# always evaluates left-to-right
  • C# always short-circuits evaluation
  • Assignments have a result
  • You can write some mind-bogglingly awful stuff in C# (not very useful)

Let's take a look at these one-by-one and by the end you should be able to work out how that particular atrocity manages to produce the right results.

Assignments Have a Result

The first thing we really need to understand is that assignment operations return a value. I know that appears to make no sense but it's true. The value they return is the value that's assigned. So variable = Math.PI for instance assigns the value of PI to the variable and also returns the value of PI. Usually the runtime just throws this return value away.
Want to test this? It's easy enough to prove.


//let's be explicit about creating 2 doubles with values 0.
double first = 0, second = 0;
//assign the first to a constant
first = Math.E;
Console.WriteLine(String.Format("First [{0}], Second [{1}]", first, second));
//assign the second then assign the result of the assignment to first
first = second = Math.PI;
Console.WriteLine(String.Format("First [{0}], Second [{1}]", first, second));
//Output...
//First [2.71828182845905], Second [0]
//First [3.14159265358979], Second [3.14159265358979]

What's the practical use of this? Beyond being a handy syntax for assigning multiple variables the same values (or derivatives thereof) I'm not sure. Using the feature in conditional statements is convoluted, confusing and should definitely by avoided - even if the values are boolean.
if( bool1 = bool2 ) can easily be read as if( bool1 == bool2 ) but the two pieces of code do very different things. Conditional statements are not intended to modify things, they're intended to test them. Best to keep it that way.

Guaranteed Left-To-Right Evaluation

C# always looks at the left hand side of a conditional expression first, then it works its way towards the right. This might seem obvious but C did not guarantee this.

What use is it? Well it has a few uses on its own but they're mostly quite specialised. It's main use is when combined with the last language feature.

Short-Circuit Evaluation

Let's look at a simple if statement...

int a=5,b=7
if(a == 0 && b == 7)
    do_something();

We know it will be evaluated left-to-right so the term the runtime will look at first is a == 0. We know that we set a to 5 so this will evaluate to False. The other term of the if statement, b == 7 is ANDed with the first - the entire expression can only evaluate to True if both sides evaluate to True.
The left hand side evaluates to False so it doesn't matter what the right hand side evaluates to, it can't affect the outcome of the entire expression.

So the runtime doesn't bother with it. It can't affect the result so why bother wasting CPU cycles evaluating it?

The same is true of OR conditions.

int a=5,b=7
if(a == 5 || b == 7)
    do_something();

This time we've set a to 5 so the first term of the expression evaluates to True. This time though the second term is ORed with the first. True OR anything is always True so there's no point in the runtime evaluating the rest of the expression - so it doesn't.

What use is this? Well null checks are a really obvious one.


if(myObject != null && myObject.SomeProperty == someValue)

If myObject is null then the right-hand side will never execute. I must add a note of caution at this stage: some developers really don't like this construct. I think their main fear comes from C where the neither the order of evaluation nor short-circuiting were guaranteed by the language, so it could have evaluated this right-to-left or evaluated all the terms regardless, both of which would be pretty terminal.

There's also an argument that it's not clear. It is true that if badly written it can rather obfuscate the actual tests, but any badly written code can obfuscate the functionality (see the terrible if statement at the top of this article). My advice would be that if the relationship between the "gateway" test and the one that it's shielding is not immediately obvious then split it out into multiple if statements. Here's an example of something that's unclear :-

if(myFirstObject.SomeMethod() != 37 && mySecondObject.SomeProperty == someValue)

You might know that if SomeMethod() doesn't return 37 then mySecondObject will be null but someone else reading your code probably won't and could easily break it. This should be more explicitly coded and properly commented.

Another use - and this one requires some thought - is optimisation. If you have a relatively expensive test and a relative cheap one, you might want to order your conditional statement carefully to save a few CPU cycles.

if(myObject.IsActive && Math.Sqrt(Math.Pow(targetX - myObject.X, 2) + Math.Pow(targetY - myObject.Y, 2)) < 100)

Square roots are quite expensive to calculate whereas the boolean is easy to test. So we put the boolean test in first and if this is False then we won't bother evaluating the more expensive right hand side.

Conclusion

If you didn't know before you now have the tools to work out how my little abomination toward the top of the article works. It uses 3 language features.

  • Guaranteed left-to-right evaluation means we can be sure what order an expression is going to be evaluated in.
  • Short-circuit evaluation means that we know the runtime won't even run a test unless its outcome can affect the entire expression. We can use this fact to optimise code and even to stop the runtime executing tests that might throw an exception.
  • The fact that assignments have a result isn't very useful and can cause a lot of problems. It's probably best avoided.

Beating the Winter Blues.

Reading Time: 2 minutes
Woodbridge Harbour

It’s depressing – the end of September has gone and the nights are drawing in. Soon we will be getting up in the dark. I think most of us find it a little harder to get motivated in the winter, perhaps not to the stage where we would say we were actually depressed or suffering from SAD, just a bit “meh”.

Thankfully there are things we can do to alleviate that somewhat. Here are 2 that I do…

1 – Get a “Dawn Simulator” Alarm.

I’ve got a Lumie Bodyclock Starter 3o (there are much cheaper alternatives). Half an hour before the alarm goes off it starts to turn the light on. It steadily increases the brightness so that when the alarm finally does go off it’s actually quite light in the room.

The effect is relatively subtle – I don’t wake up full of the joys of spring as the marketing material for these things implies. What I find is that I’m alert when I wake up instead of half asleep and that actually makes a big difference to the start of the day, which in turn makes a big difference to the rest of the day.

2 – Use Daylight Coloured Lights

It may be a stereotype that programmers like to sit in the dark but not all of us are like that. I’m lucky – my office environment is under my control. I’ve replaced all the lights with daylight coloured LED units. This makes a big difference too – the office is bright and cheerful even on a grey winter day. It just makes putting in a day’s work that little bit easier.

If you’re not as lucky as me you can always put a request in to your building manager to get the light colour changed. Often “daylight” units are the similar prices to other colours so  you can usually get them swapped out, if not immediately then when the units fail.

You can also try getting a daylight desk light – be aware though that when using a desk light you have to make sure that you look away from your desk a lot. It’s rather easy to get zoned in for hours and that won’t do your eyesight any good at all.

These are 2 really simple and easy things that can make a big difference in the middle of December when you start and finish work in the dark.