Wednesday, 15 June 2011

Essential Developer Principles #1–Divide and Conquer

With this post I am starting a new series in which I intend to cover a miscellany of developer ‘principles’. They are in no particular order, and I’m not promising any great regularity but I am intending to use some of the material I present here as part of the developer training where I work, so please feel free to suggest improvements or offer counterpoints.

The essence of software development is divide and conquer. You take a large problem, and break it into smaller pieces. Each of those smaller problems is broken into further pieces until you finally get down to something you can actually solve with lines of code.

If you can’t break problems down into constituent parts, you don’t have what it takes to be a programmer. Apparently some who purport to be developers can’t even solve trivial problems like FizzBuzz. They can’t see that to solve FizzBuzz (the “big” problem), all they need to do is solve a few much simpler problems (count from 1 to 100, see if a number is divisible by three, see if a number is divisible by 5, print a message). Once you have done that, the pieces aren’t too hard to put together into a solution to the big problem.

Cutting the Cake

But being a good developer is not just about being able to decompose problems. If you need to cut a square birthday cake into four equal pieces there are several ways of doing it. You could cut it into four squares, four triangles, or four rectangles, to name just a few of the options. Which is best? Well that depends on whether there are chocolate buttons on top of the cake. You’d better make sure everyone gets an equal share of those too or there will be trouble.

A good developer doesn’t just see that a problem can be broken down; they see several ways to break it down and select the most appropriate.

For example, you can slice your ASP.NET application up by every web page having all its logic and database access in the code behind – vertical slices if you like. Or you can slice it up in a different way and have your presentation, your business logic, and your database access as horizontal slices. Both are ways of taking a big problem and cutting it into smaller pieces. Hopefully I don’t need to tell you which of those is a better choice.

Keep Cutting

Alongside the mistake of cutting a problem up in the wrong way likes the equally dangerous mistake of failing to cut the problem up small enough.

In the world of .NET you might decide that for a particular problem you need two applications – a client and a server. Then you decide that the client needs two assemblies, or DLLs. And inside each of those modules you create a couple of classes.

divide-and-conquer-1

All this is well and good, but it means that your tree of hierarchy has only got three levels. As your implementation progresses, something has to receive all the new code you will write. Unless you are willing to break the problem up further, what will happen is that those classes on the third level will grow to contain hundreds of long and complicated methods. In other words, our classes bloat:

divide-and-conquer-2

It doesn’t need to be this way. We can almost always divide the problem that a class solves into two or more smaller, more focussed problems. Understanding the divide and conquer principle means we keep breaking the problem down until we have classes that adhere to the “single responsibility principle” – they do just one thing. These classes will be made up of a small number of short methods. Essentially, we add extra levels to our hierarchy, each one breaking the problem down smaller until we reach an appropriately simple, understandable, and testable chunk:

divide-and-conquer-3

I’ve not shown it on my diagram, but an important side benefit is that a lot of the small components we create when we break our problems up like this turn out to be reusable. We’ve actually made some of the other problems in our application easier to solve, by virtue of breaking things down to an appropriate level of granularity. There are more classes, but less code.

And that’s it. Divide and conquer is all it takes to be a programmer. But to be a great programmer, you need to know where to cut, and to keep on cutting until you’ve got everything into bite-sized chunks.

Monday, 13 June 2011

Silverlight Star Rating Control

I found myself needing a star rating control for a Silverlight application recently, and although I found a few open source ones, none of them worked quite how I wanted them to. Besides, I designed my own star shape in XAML a while ago and wanted to use that as the basis.

StarRating

In particular I wanted the ability to have half-star ratings. I thought at first it would require me to use some kind of complicated clipping construct, with a rectangle hidden behind my star, but I realised I could cheat by creating a half-star shape. Each star is a UserControl made up of three shapes – a star fill, a half star on top and then an outline on top.

I also wanted the colours to change as you hovered the mouse over it, indicating what rating would be given were you to click at any moment. This required the background of the control to be painted with a transparent brush, otherwise mouse events are only received while you are over stars and not in between them.

The biggest difficulty was making resize work. Path objects can be a pain to resize. I ended up putting them on a Canvas and using a ScaleTransform to get them the right size. All the brushes are customisable (six of them), plus you can change the number of stars, the line joins (pointy or round edged stars) and the line thicknesses. You can also turn off editing to simply display a star rating.

The Silverlight Star Rating Control is open source and available on CodePlex. The easiest way to install it is using NuGet.

To have a play with the star rating control, you can try it in my (rather chaotic looking) test harness below:

Saturday, 11 June 2011

MSBuild task to update AssemblyVersion and AssemblyFileVersion in C# files

A while ago I decided I needed an MSBuild task that could update the version numbers in my AssemblyInfo.cs file. I had a search around the web, but all the custom tasks I found seemed to work in a different way to what I wanted. So I created my own.

What I wanted was a simple way to say “increment the revision number but leave other numbers the same”, or “set the version to exactly this”. So I came up with a simple syntax to let me do just that. For example:

<SetVersion FileName="AssemblyInfo.cs" AssemblyVersion="1.2.+.=" />

This means, set the major version to 1, set the minor version to 2, increment the revision number and leave the build number at whatever it was before. You can also specify a rule for AssemblyFileVersion if you want to keep them both in sync.

SetVersionTask is open source, and hosted on BitBucket. You can download the build of the latest version there, and read more detailed instructions on how to set it up in your MSBuild script.

I had originally planned to make it work for nuspec files too, but I don’t have a pressing need for that just yet. Shouldn’t be too hard to add though. Feel free to make use of it if it does what you need.

Monday, 6 June 2011

So … is Silverlight dead then?

Microsoft’s Windows 8 announcement has generated a surprising amount of controversy given that what was shown (a fancy new start menu that can be navigated using touch alone) was exactly what everyone was expecting. The only thing that could conceivably be described as a surprise was that Microsoft’s offering for the slate will be the “full” Windows OS, rather than the Windows Phone 7 OS adapted for a larger screen.

Apparently you will be able to make stuff for this new touch interface with HTML5 and JavaScript. Quite how that makes Silverlight dead I am not sure. I certainly don’t see any reason to panic. Given that it is full Windows, you will be able to write apps for it in VB6, Delphi or QBasic if you really want to. If you can’t write Windows 8 apps in Silverlight I’ll eat my hat. And if there is, as expected, a Windows 8 app store, you can be sure you’ll be able to sell Silverlight apps on it (in fact, if they base it on the Windows Phone app store, then Silverlight might even be the preferred/required dev platform).

I suppose it is possible that you won’t be able to make “tiles” using Silverlight (though they haven’t announced that you can’t), but I can’t get too worked up about that. I don’t want my applications consuming loads of memory and CPU cycles before I load them. Tiles should only be doing minimal processing.

Which brings us to the question everyone is asking. Is Silverlight dead?

When people call a technology “dead”, what they often really mean is “stable” and “mature”. I still develop WinForms apps on a daily basis. The API is effectively complete. It hasn’t had any meaningful new features for years. But it is a mature framework. It does what it does well enough, and if Microsoft were still actively trying to shoehorn new features into it that would be a bad thing. After a while, what is needed is not new features, but a new development paradigm.

WPF was, at first, that new paradigm, making it easy to do what was a nightmare in WinForms. And it followed a similar path to maturity. It’s got all the main capabilities you need to build impressive looking LOB apps. Microsoft got some things right with WPF, but like WinForms, it too has its limitations. I am not concerned that there isn’t a vast number of new features being announced for it every six months.

And guess what, Silverlight is on the same trajectory. Early releases picked up new capabilities at rapid pace. The fact it was chosen as the Windows Phone 7 dev platform has given it a new lease of life. But already it is reaching the stage where new versions are more incremental than revolutionary. That’s a good thing – the technology is approaching maturity.

To summarise: no need to panic. Keep building apps with the most appropriate technology that is available now. Those apps will continue to work just fine for years to come. Don’t worry that new technologies come along every few years that seem to “kill” older ones. I for one am glad that I am not currently developing using Visual Basic 16 or MFC version 23. And in 5 years time, I fully expect that there will be something even better than Silverlight to write Windows apps in. If there isn’t, it will be Microsoft, not Silverlight that is dead.

Sunday, 29 May 2011

Development process signal to noise ratio (a rant)

In the world of audio recording, maintaining a high signal to noise ratio (SNR) is vital. Signal is the singer’s voice; noise is the traffic on the road outside. Signal is what we want to record; noise is what we don’t.

Just as noise can get introduced at any stage in the audio recording process, degrading the signal quality; the software development lifecycle has many points at which noise can be introduced. The only difference is, that the signal is information rather than sound. In software development, signal is information that is of use to me; noise is information that wastes my time.

In the audio world, if the signal to noise ratio is too low, it becomes simply too difficult or distracting to keep listening. The same is true with information. A low SNR to ratio bores people into switching off.

Here’s five areas in the software development / business process that you need to watch your SNR in…

Meetings

As a general rule, I dread meetings. They get me away from what I would rather be doing (coding). A meeting is maximally useful if the information that flows within it is relevant to all those present. Meetings to tell people things they already know, or that they don’t need to know, or that only one or two people need to know, are invitations to daydream, resulting in attendees missing the little that could have benefitted them.

The worst offenders are the “weekly” meetings, or meetings that are required by some kind of process (“kick off” meeting, “release” meeting, “checklist checker checking meeting”). If you attend a 90 minute meeting with only 5-10 minutes having relevance to you, something is wrong.

Talking in detail through everyone’s weekly progress, or everyone’s holiday plans, or everyone’s tasks for next week, or every open bug, or every support case, is likely to be relevant only to the person who organized the meeting. For everyone else, the meeting SNR is minimal.

Documents

Software documents, particularly those created from templates, also often suffer from poor SNR. Instead of getting right down to business telling us the crucial facts, we have to wade through pages of boilerplate sections marked “Not applicable”.

In one company I worked for, there were several pages in every software design document we ever produced devoted to the utterly irrelevant topic of PCB layout. If the first section of your document that contains useful information is numbered 4.6.12.5, something is wrong.

Documents with low SNR actively discourage people from reading. And the less likely anyone is to consult your document, the less motivated you are to write good documentation, resulting in a vicious cycle.

Presentations

Presentations can have terribly low SNR. A favourite example is presenters who try to follow the rule that says: “Tell people what you are going to tell them, then tell them, then tell them what you told them”.

Fine advice, but not when they interpret this as “tell people that you are telling them what it is that you are going to tell them, then tell them that you are telling them the things you told them you were going to tell them, and then tell them that you are telling them that you have finished telling them the things you told them you told them you were going to tell them.” Instead, use your introduction to make us want to hear what is coming next.

As with meetings, any attempt to exhaustively cover a topic in a presentation is a mistake. Don’t show me every possible graph and chart from last quarter’s financial results. Don’t show me every feature and configuration option. Show me something interesting. Leave me wanting more at the end of your presentation, not praying for it to end.

Comments

Comments in source code are also prime offenders for low SNR. Comments that state the obvious, or are sources of misinformation soon train the developer to completely ignore comments. It’s like the boy who cries wolf. Soon no one is listening anymore. The one really helpful comment you write might as well be invisible. No one will read it.

Comments are like footnotes in a book. Most readers will pause to see what a footnote says the first time they encounter one. But if what they find there is of no relevance or interest to them, they will soon train themselves to stop looking.

Code

What about your code? Surely that is all signal right? After all, we can’t delete 50% of the lines and leave the behaviour of the code intact. But the truth is that code can be written in a very noisy way. This happens when so much code for logging, or caching, or error handling, (or whatever) is mixed in that the structure and intent of the method in question is obscured from view.

The solution is simple: write clean code. Extract each task out into small, well-named helper methods or dependencies. This allows people to see the “signal” of what is going on, and only delve into the details that are of interest to them. Implementation details are usually noise.

Summary

Stop writing comments that are just noise. Delete comments that are wrong. Refactor “noisy” code out into helper methods. Learn what clean code is. Hold fewer and shorter meetings. Write shorter documents. Tell me what I need to know. Stop wasting my time.

Saturday, 28 May 2011

NAudio and NuGet (and the x64 problem)

Several people have contacted me recently asking when NAudio will appear on nuget.org. The short answer is, hopefully soon. For the longer answer, read on…

The need for a decent build process

To release NAudio, there is a bunch of stuff I have to do, such as remembering to run all the unit tests and manual tests on all the operating systems and soundcards I can get my hands on (which in truth is a pretty limited selection). I then have to create a bunch of zip files for the binaries, the demo apps, and the source code to go on CodePlex. Then there is the release notes. A NuGet package adds yet another thing to a process that I would rather not be spending my free time on.

The hassle of doing all this means I don’t release as often as I should. However, I have created an MSBuild script for NAudio now that should make it a lot easier for me to create releases. And yes, one of the things it now does is creates a nupkg for NAudio.

The need to decide on a version numbering strategy

The approach to versioning I have taken with NAudio is that there is a major and minor version, and then the third digit gets updated regularly (used to be every checkin, but I have got lazy). If I am to release NAudio to nuget, I need to decide now how I will version it. Ideally I just want the public releases to be called “1.4”, “1.5” etc. But when I do bugfixes, what should their package number be? It doesn’t seem right if the package is 1.4.1 but the NAudio.dll version is 1.4.272.0. There seems to be a mixture of choices taken by other libraries on nuget.org, but I guess the safest is simply to use all four numbers as the package version and eliminate any possible confusion.

The need for an updated NAudio 1.4

After releasing NAudio 1.4 RC a while ago, I spotted a couple of bugs that I would really like to fix before calling it NAudio 1.4 final. Since I suspect that NAudio will get a lot more downloads once it is available on nuget.org, I want to make people’s first experience as good as possible.

However, since I am well into writing the code for NAudio 1.5, I will need to create a branch to back-port the crucial fixes in. I’ve contacted CodePlex asking them to turn the NAudio repository into Mercurial so I can branch more easily. Hopefully once the conversion has taken place I can create my branch and start work towards an updated 1.4 release that can go on nuget. There will however be one outstanding issue remaining…

The need to decide on an approach to the x64 problem

The NAudio.dll is currently compiled with the platform target explicitly set to x86 . This means if your application is running as a 64 bit process it will fail when it tries to load NAudio. You need to mark your main project as x86 too for it to work.

There are two reasons for this. The main reason is that since my development environment is x86 (soon to change – I have ordered a new laptop and will finally enter the world of 64 bit), I cannot be sure that the interop all works properly in x64, even though I have heard reports that the vast majority of it is good to go on both architectures. However, until I am sure that all the interop (and there is a lot of interop in NAudio) is safe in Windows x64, it is easier for me to simply enforce running as a 32 bit process.

The second issue is that NAudio uses ACM codecs to perform its MP3 decoding, and I have heard rumours that when running in 64 bit windows, not all your ACM codecs appear. I will have a chance to test this for myself in the near future.

Going forwards, it may be easiest to unset the x86 only flag on the NAudio DLL and just strongly recommend to people that they set it on their calling executable. We could actually do this for people using nuget’s ability to use PowerShell to automate Visual Studio. But I would rather not fiddle with people’s project settings in this way.

Conclusion

I think NuGet is a brilliant development for the .NET open source community and I can’t wait to get NAudio on there. But it might be a few more weeks yet before I have sorted my own build and release processes out.

Wednesday, 25 May 2011

NAudio and Mercurial

I am on the verge of upgrading the NAudio CodePlex project to use Mercurial for source control instead of TFS. Like many CodePlex developers I have been using TortoiseSVN since CodePlex allows you to access your project as though it were a Subversion repository. I prefer this to having to install the Team Explorer Client, which puts source control bindings in my csproj files, making them a pain to open for those without access.

I have converted a number of my other open source projects on CodePlex to Mercurial recently, and the process has gone very smoothly, and I am beginning to think that Mercurial offers a lot more benefits than the TFS/SVN model.

Easier Acceptance of Patches

For a long time I was completely oblivious of the fact that people were submitting patches to NAudio, because Codeplex didn’t send me any automated notifications. And often I don’t have time to review a patch straight away, meaning that by the time I get round to looking at it, it doesn’t merge into the latest code.

Then there is the fact that over 50% of patches I receive either contain a bug, or break some aspect of existing behaviour. I would like the ability to work with patch submitters to get their code fully ready for integration before accepting the patch.

Another benefit is that it allows for contributors to get their own name attached to checkins, without having to give them checkin privileges to the central repository, since I can pull from them, make any minor changes needed, and then push to CodePlex. It means contributors can get the credit for features they add (and the blame for bugs they introduce!).

Possibility for Forks

Finally, whilst I do often accept user contributed features into NAudio, sometimes the feature is too obscure to be considered for the core library. With Mercurial on CodePlex, people can publish their own extensions and special versions as forks, and retain the ability to pull in bug fixes and new features from the latest branch.

Need for Branches

A while ago I released NAudio 1.4 RC. Since its release I have discovered and fixed a few bugs that really ought to be back-ported into NAudio 1.4. However, I have no branching structure at the moment – NAudio is just in a single folder. Although TFS has branching support through creating a brand new folder containing a copy of the entire codebase, I prefer Mercurial’s approach which keeps the branch hidden from view unless you really need to work with it. I anticipate that only critical bugfixes will be done on previous releases, so the use of branching will be minimal in the central repository.

Better Offline Development

Often when I am working on NAudio, I will want to make fairly large changes before checking into the central repository. The trouble with this is that I want to make regular small checkins, so I can easily roll back if I go down a wrong path. Mercurial makes this very easy, essentially giving me my own local branch to experiment in before commiting to the central repository.

Also, since I try to test NAudio on all the different OS’s and soundcards I have available to me, I often need to sync code between two computers without going via the central CodePlex repository. Mercurial makes this easy.

Backup

One final thing. In its early days CodePlex had a disaster where they lost all their source control history. That’s why the NAudio history doesn’t go back earlier than April 2007. I think they have much more reliable backup processes in place now, but it would be nice to know with Mercurial that I would have a full backup of the checkin history if they ever lost it again, or if I felt the need to host elsewhere.

Also while the subversion to TFS bridge they use is good, it is not foolproof. A recent server upgrade meant that my local subversion repositories lost their ability to commit back into CodePlex, requiring me to check out to another folder and manually copy my changed files across.

Disadvantages?

Are there any disadvantages to using Mercurial? One slight issue is that Mercurial never forgets anything, which of course is normally a good thing for a version control system. But if I accidentally checked in a large WAV file for example, that would vastly increase the download time for a repository clone, even if I deleted it in the very next check-in. There are ways to do history rewriting, but it requires contacting the CodePlex admins and getting them to do it for you.

Another slight issue is that when you switch from TFS to Mercurial on Codeplex, it loses all the stats of how many downloads each revision had. Any links to specific versions of files posted in forums are also broken. I suspect I will have to manually re-associate releases with their new changeset IDs too.

The only other TFS benefit over Mercurial that I can think of is that in TFS you can modify a checkin message

Conclusion

I’ll probably be going ahead with the move soon. If anyone has any objections, or cautionary tales to tell, now is the time to speak up.