Good Refactoring / Patterns For Simple UI Logic?


I’ve got a chunk of C# that sits inside of a very simple form. The form downloads an update from a web page – one of two possible downloads, based on which one is available – and shows a message to the user saying it’s done. The basic rules for which one to download are:

  • If a software update is available, download it, highest priority
    • After a software update has been downloaded, exit the app immediately so an external process can unpack it
  • If a data update is available, only download it if a software update is not available
    • After a data update has been downloaded, show the data

As this is a very small application with very simple process and no real business logic, I’ve coded the majority of it straight into the form, in a method that runs in a background worker. The code works and does everything it needs to do, but it’s getting ugly and needs some TLC to refactor it into something more manageable and easier to maintain.

private void DownloadUpdates()
{
try
{
SetProgress(5);
MessageLabel.Do(ctl => ctl.Text = AvailableUpdate.DownloadingUpdateLabelText);
//software updates always take precedence over data updates
if (AvailableUpdate.SoftwareUpdateAvailable)
{
SetProgress(5);
UpdateSoftware();
SetProgress(100);
this.Do(frm => frm.Close());
}
else
{
if (AvailableUpdate.DataUpdateAvailable)
{
SetProgress(50)
UpdateData();
MessageLabel.Do(ctl => ctl.Text = "Complete");
SetProgress(100);
Cancel.Do(ctl => ctl.Hide());
ContinueButton.Do(ctl => ctl.Show());
}
}
}
catch (Exception e)
{
// error handler code here
}
}

</div> </blockquote>

(Note: For a description of the .Do() method shown here, see my post on async control updates)

As you can see, there are a few nested if statements in here, some possible duplication, and a generally ugly mix of UI and process. In the past, I would have looked at a few basic options to remove the if statement and clean this up by moving the process into separate classes with events that tell the UI when to update with what information. Since this application is so small, I’m not sure I want to go down that path. There’s not a lot to this, honestly, other than figuring out which file to download and what to do after the download completes.

Given all that – including the small nature of the app – what are the patterns you would move to and suggested refactorings that you would take in this situation? How would you clean up this code, reduce duplication (if it’s reasonable to do so) and make the easier to work with and maintain?

I have several ideas, of course, but I want to see what I can learn from other people’s refactoring and clean up ideas. Post your suggestions to a code sharing site such as Gists or Pastie, then link to them in a comment, here.

Bootstrapping The .NET Framework Without An MSI Installer