• ICanHasCheezburger interface naming style

    01 Oct 2015

    One of the things I often struggle with when writing code is naming things. Naming things well is especially important for interfaces, they're likely used in more places than the concrete types in a loosely coupled OO system.

    One guideline I've found that helps me is something I like to call the "ICanHasCheezburger naming style". I typically start all my interface names with I (most of my code is C# at the moment), so that part is easy - after that, you just describe the specific reason that the interface exists.

    So, if you're writing something for getting the GPS location on a phone - instead of calling the interface something like ILocationManager, call it IProvideLocation or ILookupLocation. It makes it very clear to anyone reading the code what the responsibility of that interface.

    Sometimes I might up with a single concrete class implementing more than one of these interfaces, because they pretty much always end up as Role Interfaces and that's fine. I like to keep my interfaces narrow if I can. However, the main thing this avoids is accidentally bloating the interface as time goes on. It's much harder to allow yourself to expand the scope of something called IProvideLocation than it is to expanded the scope of ILocationManager - which means you end up following the Interface segregation principle with very little effort.

  • UK "bank grade" SSL

    06 May 2015

    After reading Troy Hunt's "Do you really want “bank grade” security in your SSL? Here’s how Aussie banks fare" post, it made me wonder how well banks do over here in the UK. I'm expecting them to be about the same, because I can't think of a reasons for UK banking to be particularly better or worse than Aussie banks.

    After dropping a few bank URL in to the SSL Labs test, showing the same properties as Troy, we get:

    Bank Grade Still supports SSL 3 Still supports SHA1 No TLS 1.2 support Still supports RC4 Forward secrecy support POODLE vulnerable
    Santander B Pass Pass Pass Fail Fail Pass
    Barclays B Pass Fail Pass Fail Fail Pass
    Co-operative Bank B Pass Pass Fail Fail Fail Pass
    Royal Bank of Scotland B Pass Fail Fail Pass Fail Pass
    HSBC B Fail Fail Fail Fail Fail Pass
    Lloyds C Fail Fail Fail Fail Fail Fail

    I know Santander isn't a UK bank, but it s popular bank on the UK high-street.

    It's nice to see there's no F grades here, but the lack of A grades is disappointing - as is the POODLE vulnerability with Lloyds. Hopfully they'll work to fix that in the near future.

  • Richard Feynman and Specification by Example

    23 Oct 2014

    I think Richard Feynman would have been a fan of Specification by Example

    Taken from Surely You're Joking Mr Feynman

    I had a scheme, which I still use today when somebody is explaining something that I'm trying to understand: I keep making up examples. For instance, the mathematicians would come in with a terrific theorem, and they're all excited. As they're telling me the conditions of the theorem, I construct something which fits all the conditions. You know, you have a set (one ball) - disjoint (two balls). Then the balls turn colors, grow hairs, or whatever, in my head as they put more conditions on. Finally they state the theorem, which is some dumb thing about the ball which isn't true for my hairy green ball thing, so I say, "False!"

    If it's true, they get all excited, and I let them go on for a while. Then I point out my counterexample.

    "Oh. We forgot to tell you that it's Class 2 Hausdorff homomorphic."

    "Well, then," I say, "It's trivial! It's trivial!"

  • Refactoring in the past with git

    31 Jul 2014

    Sometimes you get half way through a task when you realise you need to do some refactoring before you can continue. One option is to just do the refactoring as you go, but if it's more than a trivial refactoring that will make it hard work for anyone reviewing the code. They'll need to untangle the refactoring from the feature implementation.

    If you're using git, you have another option. Commit your unfinished work as "WIP" on a new branch then checkout the previous commit - the one before you started this task.

    Then you can do the refactoring without your feature work getting in the way. When you've finished, you just commit that refactoring work with a nice commit message and then switch back your WIP branch.

    Once you've done that, you can rebase your WIP onto the refactoring work and carry on where you left off.

    It's as if you travelled back in time to do the refactoring just before you needed it.

  • NSubstitute speed-bumps when using Returns()

    16 Jul 2014

    When using NSubstitute, to make it possible to do things like substitute.Foo().Returns(7), calling Foo() on a substitute sets some internal state that says "Next time Returns() is called, I'm the method you're setting the return value on". This means that if you call anything on any substitute inside a call to Returns() you'll end up in a mess.

    I've ran into problems with this when doing stuff like:


    This kind of problem can take a while to track down. To fix it, you need to assign the result of CreateSomethingThatUsesNSubstitute() to a local first. e.g.

    var theResult = CreateSomethingThatUsesNSubstitute();

    Once you've done that, everything should work as expected.

  • Maze refactoring challenge (C#)

    27 Sep 2013

    A long time ago, when I was new to the concept of refactoring code, one of the practice projects that I tried was cleaning up some really horrible maze generating code. “Horrible” in that it was a BASIC program ported to Java.

    Also a long time ago, I converted that Java port over to C#. If you want to try that version yourself, you can get the code from GitHub.

  • Methods should “do one thing”

    16 Sep 2013

    I’d often come across the advice that methods (and classes) should “only do one thing”. That advice seemed almost ridiculous to me. e.g. saving to a file, you need to

    1. Open the file
    2. Write the data
    3. Close the file

    So that’s three things. Then there’s error handling on top of that, which should count as another ‘thing’. So I could never see how to follow that advice.

    However, I’d seen this guideline often enough that I also thought "a large group of smart programmers seem to believe this is a good idea". I’m (hopefully) not an idiot, so I was clearly missing something here.

    It wasn’t until reading Clean Code earlier this year that it finally clicked.

    What “doing one thing” really means

    Clean Code talks about “doing one thing” in terms of levels of abstraction. This makes much more sense to me. Everything inside a method should be one level of abstraction below the method itself, which also means everything inside the method should be at the same level of abstraction. As Clean Code says:

    “If a function does only those steps that are one level of abstraction below the stated name of the function, then the function is doing one thing. After all, the reason we have functions is to decompose a larger concept (in other words, the name of the function) into a set of steps at the next level of abstraction.”

    After it clicked, I switched to thinking about it as meaning "one level of abstraction per method" which is something I can both understand, and agree with. It’s still hard to follow that guideline all the time, but at least I now know what I’m aiming for. Which is pretty close to what I’d been aiming for already.

    As Clean Code also says:

    “Mixing levels of abstraction within a function is confusing. Readers may not be able to tell whether a particular expression is an essential concept or a detail. Worse, like broken windows, once details are mixed with essential concepts, more and more details tend to accrete within the function.”

  • StringFormat bindings only work when the target type is string

    24 Jan 2013

    Recently I had a problem putting some text into a WPF MenuItem. The binding in the Xaml was something like

    <MenuItem Header="{Binding FileName, StringFormat='Open {0}'}" Command="{Binding Open}"/>`

    It turned out that it wasn’t working because Header is a Content property, but the StringFormat binding extension only works when the target of the binding is of type string, such as TextBox.Text.
    I’d never seen this mentioned anywhere before hitting this problem.

    So, for a MenuItem you need to use the HeaderStringFormat property instead. E.g.

     <MenuItem Header="{Binding FileName}" HeaderStringFormat="Open {0}" Command="{Binding Open}"/>

    For other controls you may need to set the Content property to a TextBlock and then bind to the Text property of that.

  • Using Rx to detect frozen UI

    24 Jan 2013

    A common problem for some applications, and a very annoying thing for users, is when the UI thread is off doing some work that takes longer than expected – and it leaves the user unable to do anything because the application is frozen.

    I wanted to detect when that happens in a desktop WPF app, which feels like a good fit for an Rx based solution.

    First of all, we need to notice when our application is unresponsive. If our UI thread is free to process messages, then everything is fine. But if it takes too long to process them, then we have a frozen UI problem.

    So if we periodically ping our UI thread and get an answer quickly, then everything is ok. If it’s not ok, we want to record that the UI thread hasn’t answered yet, and then wait for an answer later to tell us the UI has thawed.

    Pinging the UI thread is straight forward enough with Rx. We need to set up an interval that will regularly produce values (we don’t care what the values are). Then pass those on to the UI thread. We’ll generate the values (i.e. the ping messages) on the task pool, and then watch for them on the dispatcher. Like so:


    If our UI thread (i.e. the dispatcher) is busy, then producedOnTaskPoolObservedOnUI won’t be producing any values. If it goes for more than, say, one second without producing anything them we know our UI has become frozen. When our UI thread is no longer frozen, it’ll start producing values again.

    To do that, the full code becomes:

    var producedOnTaskPoolObservedOnUI = Observable.Interval(TimeSpan.FromSeconds(0.25))
        .Subscribe(window => window.Subscribe(_ =>
                /* UI Is now frozen */
                    onNext: __ => { },
                    onCompleted: () => { /* UI is no longer frozen*/  });

    The producedOnTaskPoolObservedOnUI sequence, in an ideal world, will produce values every 250ms which means the Throttle of one second will never output anything (because the UI isn’t blocked). However, if we ever go for more than a second without producedOnTaskPoolObservedOnUI producing a value, the Throttle will let the most recent value through.

    When the Throttle does let a value through, we open an IObservable window (which is set to close the next time producedOnTaskPoolObservedOnUI produces a value). Then we subscribe to that window, so the first value indicates that the UI is frozen. After we get the first value, we subscribe again to the window – this time we only care about the sequence completing, which tells us that the window has closed (because producedOnTaskPoolObservedOnUI produced a value) and we’re no longer frozen. We can’t just always subscribe to OnComplete, because the Window() operator will produce empty windows if Throttle doesn’t let any values through.

    Now that we have “UI frozen” and “UI thawed” detection, we can do whatever we want at those points. Such as logging what the user was doing when we noticed the frozen UI.