Strongly-typed ints

Weird title, no? I couldn’t think of a snappier one, I’m afraid.

I’ve been thinking of a way to ensure that this sort of subtle bug/typo doesn’t happen:

public void MyMethod(int useCaseId)
    // Do something with the useCaseId

public void SomeOtherMethod()
    int userId = 12;
    int useCaseId = 15;
    MyMethod(userId); // Ooops! Used the wrong value!

This bug would be hard to find because there’s no compile-time error, and you wouldn’t necessarily even get an exception at run-time. You’d just get "unexpected results".

To resolve this in a simple way, I’ve experimented with using empty enum definitions. Effectively making a user id a data type (without going quite as far as a class or a struct):

public enum UseCaseId { // Empty… }
public enum UserId { // Empty… }

public void MyMethod(UseCaseId useCaseId)
   // Do something with the useCaseId

public void SomeOtherMethod()
   UserId userId = (UserId)12;
   UseCaseId useCaseId = (UseCaseId)15;
   MyMethod(userId); // Compile error!!

What d’you think?

My Opinions on “Test Driven Development: By Example” by Kent Beck

I’m trying to get into TDD, and to this end I’m halfway through reading this book:

I’m not sure I agree with *all* the principles in it though.

Beck proposes a roughly three-step method:

  1. Write a test.
  2. Write whatever it takes in the least amount of time to get the stuff to compile and run successfully (a.k.a “get to a green bar as quickly as possible”).  This apparently can include hard-coding values (gulp).
  3. Refactor to fix up your deliberately dodgy code “remove duplication”.

I understand the concept of test-first, but as a singularly scatterbrained individual, I can’t bring myself to go with “fake it ’till you make it” and “speed is more important than correct code (but only for a short while)”.  How will I remember/find those horrible bits of hard-coded code and ensure I’ve made them correct?  I think the trick to this (though it’s not said in as many words) is to write more tests that test the code from different angles until you get tests that fail with those hard-coded values, and fix them.  As a beginner of TDD, I don’t think I can be sure I’d do this effectively.  Essentially it is suggested that I write bugs into my code deliberately.  Eeeek!

What’s the point of a successfully run unit test if you know it’s testing broken code?  If you write any old code that will get the test working, you’ve totally negated the reason for the test in the first place.

Unit Test + Correct Code should equal Green Bar

Unit Test + Incorrect Code should equal Red Bar


Unit Test + Broken Code = Green Bar

I want tests that fail unless the code is correct.  While this isn’t always easy, I can’t bring myself to deliberately write incorrect code just to get a sucessful test.  If I have a green bar, what’s left to tell me what I need to do next?  As I said, apparently you just write more tests.

I prefer a different method:

  1. Write a test.
  2. Write the code that makes the test work.
  3. Refactor if I change my mind about that code, safe in the knowledge that as long as the test passes, the code is okay.

To his credit, Beck does suggest in his book that the whole idea is that you gradually learn how big your changes in-between running tests should be.  That it is a learning process.  When you know what you need to make a given test pass, you are allowed to write that “Obvious Implementation”.

I’m basically not sure I like the recommendation that the process be quite so iterative.  If you have to run your tests after each tiny change, you’re effectively introducing a compilation tax which will quickly get frustrating.

I’d love you hear how you’ve interpreted Beck’s advice for your own TDD process.  I’m sure I’m just missing the point, so enlightenment is always welcome :).

Tip for debugging console applications in C#

Sometimes in a C# console application, you want to output text to the console window for release builds, meaning Debug.WriteLine() is out of the question.  Maybe you also want the output in some sort of log file?  It would also be handy to be able to indent the output to make it clearer what your application is doing.  This makes simple Console.WriteLine() impractical, too.

If it’s an enterprise application you’d probably look at Log4Net or similar, but if it’s just a little something you’ve knocked up, then that might be overkill so try this at the start of your application:

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

The documentation for Trace and Debug gives more detail, but the great thing with this approach is you can now format your logging output in a more clear way:

Trace.WriteLine("Starting loop...");
foreach (string name in names)
Trace.WriteLine("Completed loop");

Like I said, I’m not proposing it as best practice for large-scale production systems, but for those occasions when you need to see into your application without debugging it, it might prove useful.

One status to rule them all

I’ve literally today really got into Twitter. You can find me as nbarnwell. I think it’s because I’m such a fan of the status updates on Facebook. I love the idea of a simple phrase that says what I’m thinking or doing at any time. I love the idea that I can update it easily, too.

To start with, I was using the Facebook webapp itself, but then I found that I hate Facebook. Don’t get me wrong, I love the idea of a social network site that connects me better with friends and family, I just hate the dross of so-called “applications” that have sprung up and now all but smother the very thing that makes Facebook so good.  I’ve blogged about minor points of Facebook’s usability nightmare, and I’ll blog again soon on the subject.

I wanted to get away from the clutter. The first thing I did was to knock up a small application using some code I obtained from ZapTheDingbat to update my status with a local application that takes a command line (I tried using the Facebook developers toolkit, only to find the API sorely lacking in functionality). Put that together with Launchy, and hey presto, I can update my status with no mouse clicks, no waiting for browsers to open, nothing.

So that took care of telling people about me, but what about finding out about my friends? Well fortunately, Dave Winer found the answer, and it lies in RSS feeds for status updates.

So this is all well and good, but I find myself outgrowing Facebook status updates. I think I might want to be micro-blogging properly, so I’ve signed up for Twitter. I still want to update my Facebook status (after all, that’s where my friends are at the moment), so wouldn’t it be cool if it updated with my latest tweet? Yes it would, and I happened on the easiest way to do it:

  1. In Facebook, search for, add, and logon to the Twitter application.
  2. Once it’s up and running, and you’re on the “What are you doing?” page, you’ll see a blue box containing the text “Want Twitter to update your Facebook status? Click here!”.
  3. Click it and follow any instructions.
  4. Stick a tweet on Twitter, and hey presto!

So that’s it. I’m now updating my Twitter “status” and Facebook status in one go, and I see Facebook friend updates in Google Reader along with all my other feeds, while tweets I’m monitoring using IM (Google Talk) and the Twitter website.

Now I just need to contact my mobile operator to see what the cost would be if I used SMS to post tweets more often; Twitter say:

Though you’ll never see a bill from Twitter, it depends on your text messaging plan; standard text messaging rates (such as international text messaging fees) do apply. Consult your service provider to ensure that your text plan covers your Twitter usage. Give your provider the Twitter phone number you’ll be using to see if you’ll incur extra charges. If you’re using Twitter from outside of the US, please consult your carrier to find out if you’ll incur international charges using Twitter numbers, as every provider has a different policy.

So I need to be sure before I rack up a huge bill (and I think I could get addicted to this…). Either that or I use GPRS and use the site, but that still costs a fair whack on my current call plan, and is much slower than a simple SMS.

Nearly there…

Proofreading is hard to do

Proofreading is an essential part of everyday life. I’m pretty anal about things like that, and constantly go over and over almost everything I write. The trouble is, I still notice problems with my posts after they’ve “gone to print”, despite the check-and-double-check approach I tend to take.

More worrying is when you spot a WTF in code you wrote some time ago, or yesterday. This happened to me today – while going through some code in a peer-review, I noticed that a method parameter was not being used in that method. So simple (and, I might add, in this case fortunately not an issue) and easy to miss.

I know what you’re thinking:

“Hah! If you’d written a unit test you would have found this much quicker!”

but I know already, and my point isn’t really limited to writing code. Blog posts, emails, letters forum posts, comments, you name it. How often have you only realised your mistake after clicking “Publish”?

Is one in the hand worth two in the bush?

Here’s the scenario:

You’re working on some software. You need to add some new functionality to it, and in looking through existing stuff you see the methodology in place. You don’t think it’s the best way to do it (or maybe it’s objectively incorrect for some reason), so what do you do?

a) Spend a lot of time re-working the existing stuff into a “better” way of doing it, then quickly add in your new stuff now that the framework is in place.

b) Write in the new methodology and supporting classes etc, then add your new stuff in and comment the old stuff with // @TODO: Update to new methodology.

c) Just write your new stuff in the old “incorrect” or less preferable way, sigh, and get on with the next task.

Answers on a virtual postcard please.

Personally I’ve done all three of these, with no particular favourite. That might be the answer in fact, that different situations and time pressures require you to take the easy option. I know that re-working existing code into a nice framework will provide a good footing for my new functionality, but it’s at the risk of changing or breaking existing functionality that shouldn’t have been affected.

This probably doesn’t just apply to software development, either. This year I’ve been renovating our kitchen. At one point we had the decision on whether to take the old water-damaged ceiling down or not. My options were:

a) Rip the old ceiling down, re-do all wiring in the kitchen (lights and power), put new plasterboard up, new fittings, have it plastered and paint it.

b) Put new plasterboard up over the top of the existing ceiling, have it plastered, paint it. Thus keeping the old lighting locations and meaning I couldn’t redo the electrics or put outside lights in.

c) Paint the old ceiling and get on with my life.

I went for a). Turns out that was the right thing to do, because now we have outside lights, new spotlights replace the old striplight, and we have loads more plug sockets (removing some dodgy wiring in the process), but I didn’t know that before I started.

Have I just answered my own question?