Code Review: Making a drop down list out of an enum

I’ve come across code like this a couple of times and it is rather odd:

IEnumerable<CalendarViewEnum> _calendarViewEnums =
List selectList = new List<SelectListItem>();
foreach (CalendarViewEnum calendarViewEnum in _calendarViewEnums)
  switch (calendarViewEnum)
    case CalendarViewEnum.FittingRoom:
      selectList.Add(new SelectListItem { 
          Text = AdminPreferencesRes.Label_CalendarViewFittingRoom, 
          Value = ((int)calendarViewEnum).ToString(CultureInfo.InvariantCulture), 
          Selected = (calendarViewEnum == CalendarViewEnum.FittingRoom) 
    case CalendarViewEnum.Staff:
      selectList.Add(new SelectListItem { 
          Text = AdminPreferencesRes.Label_CalendarViewStaff, 
          Value = ((int)calendarViewEnum).ToString(CultureInfo.InvariantCulture), 
          Selected = (calendarViewEnum == CalendarViewEnum.Staff) 
    case CalendarViewEnum.List:
      selectList.Add(new SelectListItem { 
          Text = AdminPreferencesRes.Label_CalendarViewList, 
          Value = ((int)calendarViewEnum).ToString(CultureInfo.InvariantCulture), 
          Selected = (calendarViewEnum == CalendarViewEnum.List) 
      throw new Exception("CalendarViewEnum Enumeration does not exist");
  return selectList.ToArray();

So, what this does is it generates a list of values from an enum, then it loops around that list generating a second list of SelectListItems (for a drop down list box on the UI). Each item consists of a friendly name (to display to the user), a integer value (which is returned to the server on selection) and a Boolean value representing whether that item is selected (which is actually always true, so it is lucky that MVC ignores this the way the Drop Down List was rendered, otherwise it would get very confused.)

Each loop only has one possible path (but the runtime doesn’t know this, so it slavishly runs through the switch statement each time). So that means we can do a lot to optimise and simplify this code.

Here it is:

List<SelectListItem> selectList = new List<SelectListItem>();
selectList.Add(new SelectListItem { 
    Text = AdminPreferencesRes.Label_CalendarViewFittingRoom, 
    Value = ((int) CalendarViewEnum.FittingRoom).ToString(CultureInfo.InvariantCulture) 
selectList.Add(new SelectListItem { 
    Text = AdminPreferencesRes.Label_CalendarViewStaff, 
    Value = ((int)CalendarViewEnum.Staff).ToString(CultureInfo.InvariantCulture) 
selectList.Add(new SelectListItem { 
    Text = AdminPreferencesRes.Label_CalendarViewList, 
    Value = ((int)CalendarViewEnum.List).ToString(CultureInfo.InvariantCulture) 
return selectList.ToArray();

There is one other another bit of refactoring we can do. We always, without exception, return the same things from this method and it is a known fixed size at compile time. So, let’s just generate the array directly:

return new []
  new SelectListItem { 
      Text = AdminPreferencesRes.Label_CalendarViewFittingRoom, 
      Value = ((int) CalendarViewEnum.FittingRoom).ToString(CultureInfo.InvariantCulture) 
  new SelectListItem { 
      Text = AdminPreferencesRes.Label_CalendarViewStaff, 
      Value = ((int)CalendarViewEnum.Staff).ToString(CultureInfo.InvariantCulture) 
  new SelectListItem { 
      Text = AdminPreferencesRes.Label_CalendarViewList, 
      Value = ((int)CalendarViewEnum.List).ToString(CultureInfo.InvariantCulture) 

So, in the end a redundant loop has been removed and a redundant conversion from list to array has been removed. The code is also easier to read and easier to maintain. It is easier to read because the cyclomatic complexity of the method is now one, previously it was 5 (one for the loop, and one for each case clause in the switch statement [assuming I’ve calculated it correctly]). The lower the cyclomatic complexity of a method is the easier it is to understand and maintain as there are less conditions to deal with. It is easier to maintain because now instead of a whole new case statement to be added to the switch statement a single line just needs to be added to the array. The redundant Selected property has also been removed.

There are still ways to improve this, but the main issue (what that loop is actually doing) for anyone maintaining this code has now been resolved.

Code Review: FirstOrDefault()

I regularly review the code that I maintain. Recently, I’ve come across code like this fairly often:


I cannot rightly comprehend why anyone would do this.

FirstOrDefault() returns the first item in a sequence or the default value if it doesn’t exist (i.e. the sequence is empty). For a reference type (classes, basically) the default value is null. So using the value returned by FirstOrDefault() without a null check is only valid for when the sequence contains a value type (e.g. int, decimal, DateTime, Guid, etc.)

In the example above if someCollection is an empty list/array/collection/whatever then FirstOrDefault() will return null and the call to the Id property will fail.

Then you are left with a NullReferenceException on line xxx but you don’t know if it is someCollection, or the returned value from FirstOrDefault() which then wastes your time (or the time of someone else who is having to debug it).

So, if the sequence must always contain items then use First(), in the exceptional event that it is empty the call to First() will throw a more appropriate exception that will help you debug faster. If it is perfectly valid for the sequence to be empty then perform a null check and change the behaviour appropriately.

What a waste of money by Currys (but win for GAME)

As the end of last year, I was at a Microsoft event where we got to see a number of new Microsoft technologies. At this event I got my first chance to have a look at the XBOX 360 Kinect. Since I’m not a gamer I hadn’t paid much attention to what a Kinect was until I actually saw one and had a play on one. Then I instantly wanted one. If you’ve never seen it, even if you are not into computer games, I would highly recommend you have a look.

Anyway, since arriving back home I decided to have a look at getting my hands on one. I’m not a gamer. so I don’t already have an XBOX 360, but since all the options were explained to me I now know exactly what I want. And what I want is an XBOX 360 250Gb HD with the Kinect sensor bar. I know I should be able to get that bundle for somewhere in the region of £300. But I’m looking for a deal. With that in mind I went looking for options. So I searched on Bing and Google.

They both return advertised links (PPC: Pay Per Click) as well as the regular (“organic”) results. So, I click on all most of them opening them in to new tabs. (Remember, I am looking for a deal, so I want to compare quickly what each of the offerings are).

Currys has a paid link with the tag line “Buy Xbox Kinect. We are in stock Reserve and Collect yours Now.” [sic] It sounds promising, doesn’t it? currys-kinect-page

So, I click the link and go looking for the price. Nope can’t see a price.

Some form of Add to Basket link, surely that’ll get me a price. Nope, can’t see that either.

Anything at all that looks remotely like some form or buy/purchase/reserve link. Anything at all! Nope. Not a thing.

I know what I want. I’m motivated to buy. All I want to know is that you’ve got it in stock and how much you want for it.

Well done Currys, you’ve wasted money on advertising a product that I cannot see how to actually buy. I got so irritated that I went to close down the tab in my browser. But… I didn’t do that. I got to thinking about how the follow up from the advert had not served its purpose. The advert hooked me in, but the website was so ineffectual that I was heading off elsewhere.

So, how do I actually buy it? There is no “buy this” call to action, so I really don’t know where to go from here. Any button I press is going to be a bit random and I have to think about what is likely to give me the best route to accomplishing my goal.

I really feel at this point that the website isn’t doing its job properly. Surely the purpose of this website is to get people to buy stuff? That’s how it makes money. That’s why Currys spend money on building the site and advertising its existence. It is so they can get people to come to them to buy stuff rather than go to a competitor to buy stuff.

Lets consider if this had been a situation where I had actually walked in to a Currys store. It would have been akin to me asking a sales assistant on the shop floor “Can you tell me the price of an XBox 360 with 250Gb drive and the Kinect Sensor bar?" and instead of answering my question they wax lyrical about what a great product it is.

I scroll down the page scanning any text for things that look like links or buttons. There are some pictures with “Find out more” links below each of them. Two of them actually have the sensor bar on it, one of which also has the console on it. I actually had to open both links up to figure that out because at scanning speed they look pretty similar. It is only when I’m analysing my actions do I really consciously take in what the difference is.

currys-kinect-findout-moreOnce I get to the correct page I’m presented with a grid of pretty similar looking pictures. At least this time there is a description below each of them and a price (Finally, I’m getting the information I actually wanted). However, my issues with this website are not over. Since there are several similar bundles which vary only slightly from each other by the type of console and by the packaged games. The graphics are too small to see what the difference is in the games and the consoles all look alike I need the text to tell me which is which. The descriptions pretty much all say “MICROSOFT Xbox 360 Came Console with…”, occasionally it will say something else such as “MICROSOFT Xbox 250Gb Bundle with…”

This is not giving me what I want. In fact, Currys are doing themselves a disservice as well. Some of the titles that just say “Xbox 360” without reference to the type of Xbox are actually the 250Gb version, so at a glance I would skip past them because I’ve also seen other descriptions that say “250Gb” so I am assuming it is a lower spec model that I’m not interested in.

Had I not been piqued with interest about the issues with this website I’d have left a long time ago. Instead, I took some time to understand what was actually going on and highlight them.

I’m guessing there was a meeting at some point to discuss the design of the website. At this meeting various aspects of the site were discussed. In the rush to get the site out of the door short cuts were taken. Certain things weren’t thought about properly.

The “Find out more” button actually takes you to a page where you can browse the products relating to the page you’ve just come from. Why not tell me that? I’d have been much more interested if the link had mentioned that I’d see prices, bundle options or what not. Yes, technically I am finding out more, but it didn’t really inspire me to find out more, which is more my point.

The product names in the page that allows you to browse the products are all clipped. I’m guessing that at some point a graphic designer put together the some visuals to show how the page should look. A web developer converts that into a working site. The visuals show two line product names but the developer sees that some product names are too long to match the visuals, so the product names get clipped and thus rendered (in situations were there are very similar product bundles) next to useless. Again, time is probably very tight. An unforeseen situation early in the project has now come to light. There is no time to redesign the visuals so the next best solution is taken. That’s to force the product names into the space provided.

DidI buy from Currys now I spent all that time analysing their site? No. Had an interest in usability not caused me to have a think about what was going on I would have left long before. In the end I bought my XBOX 360 Kinect with 250Gb HDD from GAME… in store! And, you know what? When I was looking in store I couldn’t see an XBOX 360 with 250Gb HD and as I  was searching a sales assistant asked me if she could help. I said I was looking for the version with the 250Gb HDD and she said that they didn’t have any left, however
if I bought the HDD as a separate item at the same time as the XBOX they would discount it so that it was the same total price as buying the model with the 250HDD included. Fantastic! Oh… and they knocked roughly 25% off each of the Kinect games we bought to get going with.

Tesco, Your car wash sucks

Earlier today I was at Tesco to refuel my car and I noticed that it was a bit overdue for a wash, so when I paid for my fuel I also purchased a voucher for the car wash. It was the premium super-duper all singing all dancing wash for £6.

When I drove round to where the car wash was there was a queue of three people in front of me so I had to wait. There was a chap at the jet wash too and I noticed that he was much slower. By the time my turn came around he was still there washing his car. In fact, by the time I wash finished he was still washing his car, he must have put much more money in that machine than I did for the car wash. In hindsight, I think he took the better decision. Why?

Share photos on twitter with TwitpicWhen I got home, I went to open the boot to retrieve my shopping and I noticed that the back of the car was still dirty. Sure, bits of it were clean, and all of it was still wet, but it was obvious that the bushes on the rollers don’t clean very well. Or maybe they don’t clean cars with near vertical rears (like the Toyota Yaris) very well. I could still wipe my finger through the dirt. And here’s a picture just to show you. (You can click the image to see it full size and you can see my finger mark in the remaining dirt)

All I can say is that I’ll not be back to Tesco to use their car wash again. If I do find myself there, I may just use the Jet Wash like the other chap did. That seemed the more sensible solution.

Technology Trends – October 2010 update

Around this time last year I wrote a blog post showing technology trends for browsers and operating systems as reported by Google Analytics for my blog and some mainstream websites.

Since then the world has moved on and the trends continue to evolve. New technology arrives, old technology slowly withers.

For the moment, it is interesting (to me, at least) to see what the trends are for my own blog.

Operating System

Windows XP is fading, not as fast as I’d hope, but still it is now below 50% of visits. On the other hand Windows 7 is rising fast and sitting at 38% in the space of just over a year. The biggest hit is for people moving away from Windows Vista, that’s where most of the market share is being lost from.

Other operating systems, such as MacOS and Linux don’t feature very heavily, bobbing around the 2% to 5% without much real movement. I’m not completely surprised by that, my blog is mostly aimed at .NET Development which is a Microsoft developer technology.



While Operating System technology is being dominated by Microsoft they are losing share on the Browser front. While IE is still the more prevalent browser its share is being eroded, not by FireFox as I would have thought, but by Google’s offering, Chrome.

FireFox has stayed fairly steady over the last three years bobbing around the 30% to 40% mark. IE has gone from just shy of 70% to just over 40%. Meanwhile Chrome has risen from nothing to just under 20%.

Other browsers, such as Opera and Safari, don’t really make that much of an impact.


Why can't customer services actually be helpful?

I’ve noticed that when ever I have to get in touch with customer services for after sales advice then I get a really bad service. I tend to get stock answers that suggest the person who responded didn’t really read my inquiry. Often they will tell me how important I am, but that really is not the impression I get. I don’t want stock answers. I don’t want to be told how important I am when it is so obvious that it really isn’t true.

However, sometime I see examples that really make me think: Didn’t someone in management at least care enough to stop stuff like this happening.

The example I’m talking about is from Halfords. I was looking for a download of the instructions for my bike rack as I’d lost them a while ago. When I searched for them I found a forum on Halfords website attached to the product that where someone had asked that very question: “Would be it possible for you to send me a complete set of instructions for this bike rack. I have lost mine.”. Now rather than actually answer the question Halfords responded with “The Halfords Bike / Cycle carrier range are designed to be universal. The range of products will fit most cars (This carrier is not recommended for cars with spoilers) The Halfords Rear Mount 3 Cycle Carrier should fit your model of car. Halfords colleagues in any one of our stores will be able to assist you in selecting the best bike carrier for your needs and provide fitting if required

Halford's forum

Ummm… okay. That’s just paraphrasing the product description already.

Luckily, someone, another customer I presume, was at least more helpful and showed how to find the instructions on the website. More helpfully, they also included a direct link to the instructions to make it easy.

Why couldn’t Halfords have done this? Why did they think they could get away with fobbing off the customer with stock drivel?

O2, please train your store employees

Last week I changed the tariff on my phone to better suit my usage. However, it turns out that by changing the tariff I also needed to change some settings on my phone. So, when the old tariff cut out, so did my 3G connectivity and I lost internet on my phone for a couple of days until a friend of a friend who happens to work for O2 explained what I needed to do to get it to work. Up until then, since I had made no modifications to my phone, I had be blaming O2’s network infrastructure.

Here is a summary of the tweets I made about it:

  • 4/March:
    • Don’t have a data network available. Most irritating @o2. Where’s my 3G network?
    • Still no data network. @o2 what are you doing. All the way from Glasgow to Edinburgh an no data network.
    • Made it all the way back to glasgow. Still no data network. @o2 get your shit together!
    • Woohoo! I have data back on my iPhone. But then I’m now at home connected to my wifi network. @o2 thanks for nothing!
  • 5/March:
    • Still no data network. @o2 you #FAIL big time! I’m moving to orange when I get a chance.
    • @kstenson No data network in Glasgow, in Edinburgh or points in between. Phone signal only. @o2 #FAIL
    • Got a data network back! One of @chriscanal‘s friends works for @o2 and fixed it for me
    • Turns out because I changed my tariff my connections settings also changed. But no one told me that!

O2 could have saved themselves a lot of frustration from me if their store employee had been told that the tariff also required a change in phone settings.

My reading list #1

I’ve decided that I need a quick and easy way to remind myself of the useful articles that I’ve read recently or are on my stack to read. Since I use my blog as an aide memoire anyway, I thought why not just put up a blog post once in a while after reading something useful. So here’s the first one…


  • The Kayak Framework: An easy way to speak HTTP with .NET
    Kayak is a lightweight HTTP server for the CLR, and the Kayak Framework is a utility for mapping HTTP requests to C# method invocations. With Kayak, you can skip the bulk, hassle, and overhead of IIS and ASP.NET.
  • REST APIs must be hypertext-driven
    What needs to be done to make the REST architectural style clear on the notion that hypertext is a constraint? In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period.
  • REST – The Short Version
    Getting a clear handle on the definition of the REST architectural style can be daunting. While there is no shortage of descriptions available, I did not find many of them helpful at first. Also, as I began talking about REST to colleagues, I often had a difficult time producing clear descriptions for the key points. Over time, however, I sharpened my summary into a version that seemed to make sense to most of my listeners. I offer here my rendition of the REST model.
  • Applying the Web to Enterprise IT
    This is a blog that contains a number of useful article on ReST.
  • Building a website for the iPhone
    This tutorial will cover the basic setup and creation of a web page for the iPhone that will detect and change the content based on the phones orientation.

Professional Development

  • Unskilled and unaware of it
    People tend to hold overly favourable views of their abilities in many social and intellectual domains. The authors suggest that this overestimation occurs, in part, because people who are unskilled in these domains suffer a dual burden: Not only do these people reach erroneous conclusions and make unfortunate choices, but their incompetence robs them of the metacognitive ability to realize it.
  • Did your boss thank you for coding yourself to death?
    Here is some perspective, you’re not doing this for yourself, you’re doing it for “the man”. Admittedly he might be a nice man, but you don’t owe him slavish commitment. Here is even more perspective, how often are you actually playing with interesting problems and cool tech and how many times are you churning out code desperately trying to get something delivered and meet some arbitrary deadline that someone has assigned to you?

Exploding out of the Closet

Ben Nunney - Jan 2010I don’t usually put personal stuff on my blog, but I have a feeling that this year there are going to be a few posts like this. My blog has always been mostly an aide memoire for me but at the same time I realise that if it helps anyone then all the better. While writing this has been a useful exercise for me, I hope more than anything that it helps others.

Yesterday a good friend of mine, Ben Nunney, posted on his blog and article entitled “Luck, Love and Dinner”. While I did post a brief reply to the blog post at the time I felt that a longer response was in order.

Ben ended his post with “I’ve talked to a lot of people … who have only recently begun to accept themselves for who they are, or who have only just started to realize that the days aren’t looking as dark as they did for Britten, Wilde and Turing.”

As someone who hid in the closet until the age of 35 I am guessing I’m one of the people he was talking about in that final paragraph. So, let me tell you my coming out story and how I got to being 35 and only just coming out.

Coming Out

Sebastien Lambla - May 2009

In March 2009 I was in London for a conference and a friend invited me along to the pub one evening and brought a couple of other friends with him. It was there that I met Seb for the first time. He was just very open about himself and his sexuality. I’d never met anyone like that before. It was Seb’s openness that allowed me to start breaking down the mental barriers in my head and I began the acceptance process.

It was mid-May that I realised I’d finally begun to accept myself. Then sometime around late late July I realised that I had stopped snacking and as a result I had begun to lose weight. I’ve always eaten comfort foods when stressed and it became obvious that hiding from myself had been causing a lot of stress.

In August I was once again in London for a conference and I met Phil (another gay friend) and Seb again. It was at that point that I decided that I should tell them and ask for advice. Unfortunately, I didn’t really find an opportune moment that weekend.

In September I was down in Manchester for a mini-conference. In the pub after the conference I asked Seb if he could spare some time to talk to me in private that evening. So, it was at about 2AM after returning to the hotel that I finally took my first steps out of the closet.

From my point of view I felt incredibly stupid. All that I had read on the internet prior to that talked about people coming out in their teens or early twenties. So it seemed to me that I was very slow. Seb was able to put me at my ease by letting me know of people he knew that had come out much later in their life than I had.

I also sought advice on what to do next. I had taken the first steps but I didn’t really know what to do next. I didn’t want to hide any more, that much I knew.

I put together a list of the people I was closest to, the people I wanted to tell personally rather than have them find out second hand. Over the following two weeks I contacted all of them. Each conversation started with me kind of stumbling around trying to find the right set of words to use. I was anxious in case I found out any of my friends were less than tolerant and this might be the conversation that could end that friendship.

I have to say that as I got through the list and I received positive reactions from my friends it gave me a new confidence that I’d never felt before. It wasn’t just tolerance, it was acceptance. I now feel closer to all those friends. At the same time, it also made me feel silly that I hadn’t done this long before.

Within about 10 days I’d personally told all my closest friends. All that was left was my parents.

I had in fact made one attempt to tell them but bottled it at the last minute. The following weekend I made a second attempt, but as I stumbled around trying to get the conversation going I bottled it again so I simply went home again. However, on the way out of my parents house I asked if I could speak to my mum sometime in the next few days.

So one evening after work I drove round to my parents house and spoke with just my mum. I figured it would be easier with just one person. Naturally, I was extremely anxious. As usual, I stumbled around a little before simply blurting out “I’m gay!”

At that point there was a pause as I looked at my mum’s blank expression for any signs of which way the conversation was about to turn. For me it seemed like an eternity. In fact I can’t have been any more than about a second or so. She then cheered up and responded “Oh, thank goodness for that. I thought something was wrong!”

How did I get here?

So, now you know the details of my coming out let me go back and tell you how I got to being 34 by the time I finally accepted my sexuality and 35 by the time I finally exited the closet.

Back when I was at school and I had the first inclining that I was attracted to men I obviously wasn’t sure what to do. I felt that there was no one to speak to. While I was trying to figure out if this was a permanent feeling or just a phase another kid in my class was outed.

Stonewall - FITIt wasn’t pleasant. And quite frankly I didn’t want to go through that so I hid. I buried my feelings as deeply as I could. Effectively I hid from myself. From that point, every time I heard a homophobic comment it just got piled in on top burying those feelings even deeper.

Perhaps if there was something like Stonewall’s FIT campaign that might not have happened. Perhaps if many things were different I would have come to acceptance sooner. It is now all water under the bridge and there is little point dwelling on it because what is done is done and cannot be undone.

Phil Winstanley - Dec 2009

Moving On

Now, this post is entitled “Exploding out of the Closet”. And you might be forgiven for wondering why at this stage.

When I spoke to Seb on the day of my coming out, he told me that he thought I was a bit of a closed person. He always had the impression that I wasn’t very open about myself. After that conversation I dec
ided that this was something that had to change. Since I’d realised that it was something that had caused me to build up a whole heap of stress I decided that I needed to be more open, not just with others but with myself too. As I mentioned above, I already knew I didn’t want to hide any more so being more open definitely be something that would compliment that.

While I never made any grand announcement on twitter (at least, that was my intention) I just just joked with the friends that already knew. My sense of humour has always included a fair bit of innuendo [^] so I expected that people would pick up soon enough.

I also attended my first Gay Geek Dinner in November followed by a tour of some of Soho’s gay bars and clubs. While there I tweeted my experience and uploaded some photos onto Facebook and Flickr. After that, I had assumed that everyone must have realised given this volume of information. Phil even commented later that I had “exploded out of the closet” (Hence the title of the post)

Incidentally, I did eventually make that grand announcement because the innuendo confused a number of people so I had to clear that up [^]. And of course, I guess this blog post acts as a grand announcement too. So, I guess I’m now well and truly out!

If you have Spotify: I’m Coming Out – Diana Ross.


I received some comments also on Twitter about this blog post in addition to the comments below. Here are the twitter comments: