Archive for March 2011

26

March 2011

Writing Comments in Code is *NOT* a Waste of Time

I was recently discussing the value of comments in code with some colleagues. After the discussion, one of them sent me a link to "Don't Waste Your Time Commenting Source Code" written by Riyad Mammadov.

I have to say I'm both shocked and disappointed that there are developers out there that have this opinion. And there seems to be quite a lot of them. I'm quite passionate about code comments because I spend the huge majority of my time maintaining/debugging/fixing code written by other people that has no comments (other than commented out code...). I waste an enormous amount of time stepping through code with a debugger, just trying to understand WTF it's trying to do.

I know some developers that always respond "The code is self-explanatory". This is a garbage excuse from a lazy programmer. There are a few reasons why this argument is not valid:

  1. It might be self-explanatory to you, but there are other developers here that may need to maintain your code, some less skilled than others.
  2. Unless you're a compiler, reading an English comment is far quicker than parsing code in your head.
  3. It's rarely clear from code why it does what it does.
  4. Reading code only helps you understand what it does, not what it was intended to do. This would be fine if you wrote flawless code. You don't.

In addition to this, we often have to write less-than-ideal code. You might find a bug, and to work around it, change some nice clean code to something a little bit hacky. If you don't comment why, there are good chances that someone will come along, think "WTF, this could be done better" and refactor your code, re-introducding the bug. A simple comment saying "Can't do this using X, because it causes Y to fail" could save a lot of time and effort.

Back to some of the points made in Riyad's article...

I strongly believe that 90% of source code comments are a waste of time

I think Riyad is a little confused between code with crap comments, and code that doesn't need commenting. I can't possible agree that only 10% of all code written is worth commenting. I might agree that only 10% of code comments are useful, but that just means the developers are failing at writing good comments, not that the idea of writing comments is bad. A huge portion of useless comments on code could be replaced with useful comments.

if you think about it, a well-designed program doesn't need comments to be maintainable

This really is tripe. Code does not convey the *reason* you are writing it. Here's an example from some real code:

// When the transition finishes, hide the screen. We don't remove it,
// because we want it to come back when the covering screen is dismissed
this.ScreenState = ScreenState.Hidden;

Without the comment, it might not be clear why the screen is being hidden, instead of being removed. Somebody that's not familiar with the code (which, six months after it being written, is everybody, including the author). The comment makes this pretty clear why the code does what it does.

If the choice is between a well-designed program without comments and a thoroughly commented but poorly architected one, I will choose the former any day of the week

I don't understand the logic here. There is some suggestion that writing comments comes with a penalty that somehow affects the architecture of your system. I think a more valid comparison whould be "Unfinished, but commented code" vs "Finished, but uncommented code", and I would absolutely take the commented code any day. It's unlikely that it'd take longer to finish a well written, well commented application than it would to try and understand thousands of lines of uncommented code.

Riyad shows some sample code to illustrate his point:

/**
 * Always returns true.
 */
public boolean isAvailable() {
    return false;
}

There's no argument here. This comment is pointless. However, there's some suggestion that because this comment is pointless, this code does not need commenting. That is absolutely not the case. The comment is crap. It should be replaced with one that is not crap.

Not writing code comments because some people write crap comments is like not writing code because some people write crap code.

Sadly the biggest loser in all this is not the developer that's not writing comments, but his colleagues. They'll struggle to maintain his uncommented code while he easily understands their well-commented code :(

16

March 2011

Windows Phone 7 Part Deux

Update (19th March): I've added some additional info I received at the end of the post.

It's been a funny week. My blog usually receives a few hundred visitors per day. This weekend, I published a post titled "Why I'm Close to Giving Up on Windows Phone 7, as a User and a Developer", sharing my frustrations with Windows Phone 7. I hoped that someone from Microsoft might read and respond to it. I wasn't really expecting the attention the post got during the last 24 hours.

The post had over 40,000 visitors in a 12-hour period yesterday (which cost me exactly £0.00 in hosting - go App Engine!) and was republished by BusinessInsider. Today, I had a call with Brandon Watson, Director, Dev Platform & Ecosystem and Ben Lower, Senior Product Manager, Dev Platform & Ecosystem.

This was somewhat unexpected.

Given they'd taken time to call me, I thought it was fair I take time to post some of the things we discussed (I hope I understood them right - the line was pretty bad). It sounds like they're taking the feedback seriously and didn't seem too annoyed with the bad PR I might have created.

Weak UK Launch / Knowledge of Operator Employees

The fact the UK launch was weak (to say the least) didn't sound like a surprise to Brandon. He explained the marketing budget was of course much smaller than in the states and that it's difficult to get info into shops (Microsoft are far divorced from the stores).

This certainly explains the poor support my colleague got from Virgin, who didn't seem to know what the Zune software was or why there had been an update. However, I wonder whether this is the whole picture - it seemed to take a long time for stores to even start getting their first handsets, so I still wonder whether a problem supplying the devices resulted in a deliberate reduction in marketing during the first few weeks.

I think this is something Microsoft must work to address. Apple have their own stores across the country, so the people selling the devices are their employees. Microsoft don't have this luxury and will need to work far harder to ensure the same quality of information and hardware availability at point of sale.

Retrieving Error Logs from Retail Devices

I brought up the issue of my SMS bug. I was willing to help Microsoft to try and diagnose the issue if they could get logs from my device. Brandon pointed out that the real issue here was that the parts of the software that allow sending of logs to Microsoft are removed from retail builds of the OS - only developer builds are able to do this.

This seems a little naive to me. There are a ton of developers out there that are very good at reporting bugs and they'll almost all have retail devices with a retail build of the OS. Brandon said he'd discuss the possibility of having this functionality included and enabled when a phone becomes developer unlocked. I think it's really important this is done if Microsoft want to be able to track down and resolve issues in a timely fashion.

SMS & Bluetooth Bugs

Brandon said he'd try and find out whether the SMS and Bluetooth bugs I specifically mentioned may be fixed in NoDo. I'm not too fussed about the SMS issue (it's never happened since), but the bluetooth issue happens daily and is so annoying to me that I'll seriously consider swapping phones if it's not addressed soon.

No Way for Users/Devs to Report Bugs

I was really frustrated with not being able to report bugs in WP7 to Microsoft in a structured way. Developer-focused products at Microsoft use Connect, but WP7 seems to be excluded. People are more than happy to help by submitting bugs, if they knew where to send them!

Ben suggested the idea of using a service like UserVoice to allow collection of issues and voting. I'm not sure why this would be better than Connect, but it sounds like a reasonable idea. Even a wiki page would be better than the "current system"!

I had a quick search and noticed there's a Windows Phone 7 Community UserVoice forum already. Not sure if this is official in any way, but if not, I do hope an official account is set up and monitored by Microsoft.

Slow Updates

This is quite a big one, but sadly, the one with least info. I suggested it was ridiculous that such a big company can take so long to get an update out. Brandon pointed out that in reality, bigger companies move slower. I don't really think this is a good excuse - if policies and processes mean it takes 5 months to release an update, then the policies and processes need improving. If a big company can't work as efficiently as a small company, then the big company should act as smaller companies.

You probably saw the recent blog post by Eric Hautala. He's the new guy, and his job is delivering updates. Eric's appointment looks like acknowledgement that Microsoft know they have work to do in this area, so we'll have to see how things evolve.

No Visibility of Incoming Fixes / Release Notes

I raised the issue of nobody knowing what's in NoDo other than the few features that have been announced. Brandon agreed that some sort of release notes should definitely be included (and are, for many of the development products) and said he'd look into it. Apple provide release notes for all of their updates, though I'd prefer to see Microsoft go one step further and publish them before the update. If Microsoft need inspiration, they should take a look at how Blizzard manage releases for World of Warcraft; Patch notes are posted and updated constantly before launch, and go into great detail. I'd love to see this kind of transparency from Microsoft.

I think I've covered the main points we discussed. The conversation was positive, but it was only talk. It'll take time to see whether Microsoft is really moving forwards. If I receive any additional info or responses from Brandon or Ben, I'll post about them.

One thing is clear from this experience; Microsoft care about developers. Apple failed to respond to the massive WiFi issues in iOS4.2.1 during the 5 months it took them to fix it, whereas within 24 hours of my post getting attention, I'd been contacted by around 6 Microsoft employees, including Brandon Watson. Let's hope the enthusiasm for getting in touch with me turns into results.

Update (19th March):

Since posting, I received a little additional info:

Connect is still being used for Windows Phone 7, though it is restricted to certain closed/invite-only programs (eg. for MO/OEMs/Devs that had development devices pre-launch). A public connect will require a better structure to deal with the volume of cases. I got the impression this is being evaluated, though no commitment.

UserVoice is also being evaluated as an option for user (non-dev) feedback. Fingers crossed if this doesn't pan out, we get an equivalent at least.

It seems that these guys agree that being big isn't an excuse for being slow, and they're committed to improving things and making things move efficiently.

MIX. April 12 - 14, Las Vegas. ;)

Also - Brandon sent me a link to the Windows Phone 7 update schedule. There's some excellent info there. I looks like MS are really taking user feedback onboard - this gives me faith :-)

14

March 2011

An ASP.NET MVC HtmlHelper Extension Method for Markdown using MarkdownSharp

Update: I changed from using MarkdownSharp to MarkdownDeep.NET and pushed the helper to NuGet to make it easier to use. Sure, it's only a few lines of code, but this way one command will import the MarkdownDeep.NET library and add the namespace to your views Web.config easily. It'll also make updates much simpler if you use it in many places :-)


One of the goals for my new blogging engine in ASP.NET MVC/Razor is to store all of my articles using Markdown instead of HTML. If you don't know what Markdown is, go read. I'll wait... If you've used StackOverflow much, you're probably already familiar with it, even if you didn't know it by name.

Since I first started working on content management systems many moons ago, there was something I disliked about using HTML to store content. Even with strides towards semantic markup, HTML felt a little clunky as a storage format. I wanted something better.

I tried many things to "solve" this problem, including creating my own XML markup for content, which I could transform into HTML for displaying on the website (or plain text, if required). This was totally stupid, and I permit for you to laugh at me (just this once, mind). My XML was 95% the same as HTML. Duh. It made more sense to just store HTML, and convert that into other formats if required, but this still didn't feel right.

As years went by, I really learned to hate rich HTML editors. They usually generate crap markup (why are there 50 divs wrapped around my content?!), and often destroyed relative paths in links and images. They also didn't work on mobile versions of most browsers, meaning I couldn't even fix simple typos when away from my computer. I was sure there had to be a better way, but unfortunately at the time of building this blog, I couldn't find one. As a result, all of the articles currently on this blog are hand-typed HTML in a <textarea>! This has an advantage of working on my iPad, but it kinda sucks. It makes me cry a little inside every time I create a post.

Enter, Markdown

Over the past few years, I've been using StackOverflow quite a lot and I've really grown to love the editor they use, which uses Markdown for formatting. The more I use it, the more I think it's what I should be using for my blog. Not only is the markup much simpler than hand-crafting HTML, it's 100% human-readable in text format and also editable on my iPad!

To test out how this could work, I decided to knock up a quick prototype in ASP.NET MVC/Razor. The code used to transform StackOverflow's content server-side was opensourced under the name MarkdownSharp, so I grabbed that. The project includes a lot of files, but these are mostly tests. The file Markdown.cs is all you need to transform text. I didn't expect it to be difficult, but it still turned out to be far simpler and far more elegant than I was expecting!

Creating an HtmlHelper Extension Method

The best way to use Markdown in an MVC view would be by creating an extension method on the Html property (an instance of HtmlHelper<T> of a view. This will allow us to transform text very easily, like this:

@Html.Markdown(Model.Body)

To do this, we need to create an extension method on HtmlHelper. We do this by using the class we'd like to extend as the first argument, but prefixing it with the keyword "this":

/// <summary>
/// Helper class for transforming Markdown.
/// </summary>
public static class MarkdownHelper
{
	/// <summary>
	/// An instance of the Markdown class that performs the transformations.
	/// </summary>
	static Markdown markdownTransformer = new Markdown();

	/// <summary>
	/// Transforms a string of Markdown into HTML.
	/// </summary>
	/// <param name="helper">HtmlHelper - Not used, but required to make this an extension method.</param>
	/// <param name="text">The Markdown that should be transformed.</param>
	/// <returns>The HTML representation of the supplied Markdown.</returns>
	public static IHtmlString Markdown(this HtmlHelper helper, string text)
	{
		// Transform the supplied text (Markdown) into HTML.
		string html = markdownTransformer.Transform(text);

		// Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :(
		return new MvcHtmlString(html);
	}
}

It's important to note that you need to wrap the resulting string in an MvcHtmlString (or other IHtmlString) to stop the framework from HtmlEncoding the output, since in this case the result is deliberately HTML that should be rendered by the browser.

In order to be able to use this method in our views without having to import namespaces, we can add the namespace to the web.config file, like this:

<pages>
	<namespaces>
		<add namespace="DanTup.Web" />
	</namespaces>
</pages>

Now in our view, we'll see our Markdown method in the intellisense once we've typed "Html.", allowing us to pass in the string we'd like to transform.

<div id="content">
	<h2>@Model.Title</h2>
	@Html.Markdown(Model.Body)
</div>

In addition to transforming data in your model, you could also pass a string in directly if you wish to keep your markup a little clearer:

<div id="sidebar">
@Html.Markdown(@"
Links
---

* [Danny Tuppeny](http://blog.dantup.com/)
* [Andrew Nurse](http://vibrantcode.com/)
")
</div>

Unfortunately if you add indenting you'll get strange issues (since indenting means something in Markdown), but for a simple hard-coded list of links/etc. this might be more elegant than ahrd-coding UL/Hyperlinks!

12

March 2011

Why I'm Close to Giving Up on Windows Phone 7, as a User and a Developer

Update: A few days after posting this, I had a call with Brandon Watson, Director, Dev Platform & Ecosystem and Ben Lower, Senior Product Manager, Dev Platform & Ecosystem. I've posted a little update here.


Note: This is a pretty long post, but it's the only way to get across why I'm suddenly so disappointed in Windows Phone 7 - a platform I've been so excited about for so long. I really hope someone on the WP7 team takes the time to read it to the end. I'm probably not unique in having these feelings.

It's a harsh title, so first, a little background...

I've been waiting for Windows Phone 7 for around 10 years. Really! See what I did there? :)

In 2001 I finished my A-Levels and got a job as a web programmer. I lived with my parents and had plenty of cash to wastespend. One of the first gadgets I bought was a Compaq iPaq. I convinced myself that it was really useful, and that it saved me lots of time, but in reality, it was horrid. The Windows operating system was slow and sluggish and the usability was pretty awful. I had to buy a sleeve that made the device twice as thick and a huge WiFi card just to allow it to connect to anything. It was crap, but I loved it anyway.

When Microsoft released the .NET Compact Framework, I was so excited. I could now write my own applications to run on this device that would fit in my pocket. Awesome! Except, it wasn't. The device was still a pain in the ass to use and the performance still sucked. The ideas were great. The execution was terrible.

It wasn't long before I picked up an XDA, so I no longer had to carry both a mobile phone and a PDA. Good times! Or not. The mobile version of Windows was still pretty bad.

Over the coming years, I bought practically every Windows mobile device I could afford. I lived in hope that this new device would be nice and snappy, and Microsoft will have improved the OS and added functionality. It never happened, but it didn't stop me throwing money at them each time, in hope.

Fast forward a few more years, and I'd been playing with Managed DirectX. The idea of programming games in C# was pretty exciting. Ultimately this became XNA, and the Zune wasn't far behind. I really wanted a Zune, but the UK launch was delayed and delayed, and ultimately never happened.

When Apple released the iPhone, I started to wonder if the reason we hadn't seen a Zune in the UK was that Microsoft were holding back to release a ZunePhone. Despite waiting and waiting, this didn't happen.

During this time (since 2001), my career was built on building web applications in Microsoft technologies. My life is well and truly in the Microsoft camp. I love .NET, I love C# and I love Visual Studio. It made me die a little inside every time I had to do some work in PHP or fire up Eclipse...

However... In 2008, I ditched my Windows-based XDA and bought an iPhone. Sorry Microsoft, I'd been waiting for 7 years, and you still hadn't delivered.

I loved my iPhone. It made me sad that there was no competition from Microsoft. I even started working on iPhone apps. I really hate Mac OSX, Objective-C, and XCode. But I had to go with the market.

Imagine how excited I was when Microsoft announced Windows Phone 7! I can ditch this Apple nonsense and develop applications in C#, Visual Studio, XNA, Silverlight! Finally, Microsoft are putting their weight into a promising mobile platform. Despite previous failures, this time, I have hope that they can really do it.

Through my company, I was able to get access to a developer WP7 device from Microsoft. The hardware was a little shoddy, but the OS was very promising. Everything was looking good!

I'd convinced my company we should be working on a Windows Phone 7 version of our iPhone apps, and I resisted picking up an iPhone4 because Windows Phone 7 was the way forward. I kept my eyes open for a UK launch date in the hope it wouldn't overlap with my holiday in Orlando, so I could get one right away. As luck would have it, the launch was announced as a few weeks before my holiday!

This is where it started to go wrong...

As we got closer to launch, I noticed there seemed to be a huge lack of advertising. I started to doubt whether the launch would be met at all. I started calling around local stores, and nobody knew anything about the launch. WTF? How can they not know about Microsoft's competitor to the iPhone?! I popped into a Carphone Warehouse over the road from the office where I work on launch day. The staff knew nothing about WP7. I called all the local Orange stores, hoping for a HTC Mozart. Nobody knew when, or if, they would be getting any Windows Phone 7 devices. Wow.

I wasn't giving up that easily, so I spent the next few weeks (getting close to my Orlando holiday) trying to track down a device. Eventually, I found that a local O2 store had HTC HD7s in stock. I rushed down there, and managed to convince them to sell me one as Pay-As-You-Go (since I'm on, and very happy with, giffgaff). I was made up! Windows Phone 7 was awesome. Just being able to pin a tile for my wife and see calendar appointments on the homescreen was enough for me to purchase it over an iPhone!

Then I went on holiday to Orlando. I took loads of geo-tagged pics, and was genuinely really impressed with the phone. Congratulations Microsoft. You've finally done it. But still, where is all the fanfare? You need to show people how awesome this phone is - then you'll sell bucket-loads!

As time went on, cracks started to show. There were bugs. Many bugs. At one point, the SMS message store for my wife got corrupt, which meant I couldn't send, or read, text messages to/from her. I got in touch with the UK WP7 developer advocate that had sorted out the developer phone for my company, and explained the issue. After many emails going back and forth I was told that there may be logs on my phone that would help Microsoft track down this issue but security procedures do not allow them to share a tool to get the logs off my device. I was instead, told to try a factory reset. This fixed the issue, but Microsoft were no closer to finding/fixing the bug.

Another pretty annoying bug was that the bluetooth randomly disconnects from my car. Frequently. About every 2-3 minutes. If I'm on a call when this happens, the call stays open, but just normally via the handset in my pocket. As you can imagine - I can't hear the person at the other end, and they can't hear me. 10-20 seconds later, it reconnects, and the call continues.

Because I preferred coding in VS/C# so much, I started work on a Windows Phone 7 game in my spare time. I even got a few colleagues to join in by creating their own games, as part of an XNA coding competition. Most of these guys had never even coded C#, never mind written a game!

My game is called Badger Quest, and currently has a few playable levels. There are no videos online yet, but you can see how it looks from the background on the Twitter page. It'll be pretty similar to Mario, though played by tapping buttons on the screen to use your abilities (jump, turn, throw, slash, etc.) which are limited in number.

As time went by, I started to have doubts. WP7 handsets weren't selling very well. The marketplace was buggy (eg. returns to the "Xbox LIVE" filter when you press "Back" from looking at an "indie" game). I started to wonder how seriously Microsoft were taking their platform. The OS was great, but how they responded to initial feedback and bug reports (and how quickly) would ultimately decide the fate of the platform.

With a huge outcry over the lack of Copy & Paste, Microsoft announced there would be an update in January that would add this. Excellent - if we don't get the bugfixes before then, they'll be in that update. All will be good.

Sadly, it wasn't good. The update was delayed. And delayed. There was zero transparency from Microsoft. Despite the rest of the company making huge strides in this area over the previous few years, Windows Phone 7 is a quiet, closed box. Nobody knew what was happening with the update, and more importantly, the bug fixes.

Eventually, an update started to roll out. Yay! Only, we quite quickly discovered it wasn't NoDo. It was a pre-update update. An update that updates the update system. Why couldn't this just be bundled with NoDo?! More annoying was that Microsoft didn't announce this update until after they started pushing it. They told us nothing about what it did.

Then it got worse. One of my colleagues was prompted to install his update. He connected his phone as described, and the update started. Then it failed. It gave an error saying his phone was not updated, and could not be rolled back. He tried all sorts of resets, with no luck. His phone was bricked. As I'd been one of the people that had suggested he get a WP7, I felt pretty bad. He spent the next day being bounced between Microsoft, Virgin and Samsung, trying to get his phone working. During this time, he could not use his phone in any way. The staff at Virgin and Samsung knew very little about WP7 and more specifically, this update. Eventually, Virgin agreed to send him a new handset.

Fast forward a few more days, and we're all still waiting for NoDo, and our bugfixes. It's been over four months and we've still had zero bugfixes. Rumours start spreading across the web that NoDo has been delayed. Again, it takes a week before Microsoft finally come out and tell us what's going on.

Hopefully if you've read this far, you now know why I'm starting to have serious doubts about Windows Phone 7. If Microsoft can't turn around bugfixes in a timely fashion, what's going to happen when people start finding exploits (and they will find exploits)?

Of course, if I'm not confident in the platform as a user, I can't be as a developer. I've put my Windows Phone 7 development on hold. I can't commit to spending more time on a platform that Microsoft seems to be sending the way of previous versions. I still believe the OS is excellent, but sadly, that's only half the battle.

I'm not giving up, just yet. I truly believe Windows Phone 7 can be something brilliant, but there are definitely issues that need addressing. To show how seriously I believe Microsoft could make this work, I've applied to go and work for the Windows Phone team via the Microsoft Careers website. If Microsoft want to make Windows Phone 7 better, here's an offer for another set of hands to test the platform. I'm serious - I'd relocate from the UK to the US to help work on making Windows Phone 7 better, because I think it could have a strong future.